Как устранить ошибку при реализации Jquery.SpellChecker в приложении .net - PullRequest
0 голосов
/ 19 августа 2011

Я попытался реализовать Jquery.Spell.Checker в приложении asp.net, но выдает ошибку, как показано на следующем рисунке.

enter image description here

Кто-нибудь подскажет мне, как решить эту проблему.

НАЖМИТЕ ЗДЕСЬ, ЧТОБЫ ВИДЕТЬ ОБРАЗЕЦ

PS:

Я внес изменения в свое приложение, но все еще не работает и отображаю предупреждающее сообщение, как показано на рисунке выше. Пожалуйста, дайте мне знать, если я что-то упустил. Код, указанный ниже:

LINK:

<link href="JQuerySpellChecker/spellchecker.css" rel="stylesheet" type="text/css" />
<script src="JavaScript/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="JQuerySpellChecker/jquery.spellchecker.js" type="text/javascript"></script>

CSS:

<style type="text/css">
body {
        margin: 1em;
        font-family: 'lucida grande',helvetica,verdana,arial,sans-serif;
}
#textarea-example {
        width: 562px;
}
textarea {
        font-size: 90%;
        margin-bottom:10px;
        padding: 5px;
        border: 1px solid #999999;
        border-color: #888888 #CCCCCC #CCCCCC #888888;
        border-style: solid;
        height: 20em;
        width: 550px;
}
button {
        font-size: 90%;
        cursor: pointer;
}
.loading {
        padding: 0.5em 8px;
        display: none;
        font-size: small;
}
</style>

HTML:

<div id="textarea-example">
    <p>
        <label for="text-content">Add your own text and check the spelling.</label>
    </p>
    <textarea id="text-content" rows="5" cols="25"></textarea>
    <div>
        <button id="check-textarea">Check Spelling</button>&nbsp;
        <span class="loading">loading..</span>
    </div>
</div>

JAVASCRIPT:

// check the spelling on a textarea
$("#check-textarea").click(function(e){
        e.preventDefault();
        $(".loading").show();
        $("#text-content")
        .spellchecker({
                url: "CheckSpelling.aspx",       // default spellcheck url
                lang: "en",                     // default language 
                engine: "google",               // pspell or google
                addToDictionary: false,         // display option to add word to dictionary (pspell only)
                wordlist: {
                        action: "after",               // which jquery dom insert action
                        element: $("#text-content")    // which object to apply above method
                },      
                suggestBoxPosition: "below",    // position of suggest box; above or below the highlighted word
                innerDocument: false            // if you want the badwords highlighted in the html then set to true
        })
        .spellchecker("check", function(result){
                // spell checker has finished checking words
                $(".loading").hide();
                // if result is true then there are no badly spelt words
                if (result) {
                        alert('There are no incorrectly spelt words.');
                }
        });
});
// you can ignore this; if document is viewed via subversion in google code then re-direct to demo page
if (/jquery-spellchecker\.googlecode\.com/.test(window.location.hostname) && /svn/.test(window.location)) {
        window.location = 'http://spellchecker.jquery.badsyntax.co.uk/';
}

CheckSpelling.aspx

protected void Page_Load(object sender, EventArgs e)
{
    string str = Request["str"];
    //string str = "goood";
    if (str != null)
    {
        string url = "https://www.google.com";
        string path = "/tbproxy/spell?lang=en&hl=en";
        // setup XML request
        string xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        xml += "<spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\">";
        xml += "<text>" + str + "</text></spellrequest>";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(xml);
        WebProxy objWP = new WebProxy("address", 1978);
        objWP.Credentials = new NetworkCredential("mysystemname", "password");
        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + path);
        request.Proxy = objWP;
        request.Method = "POST";
        request.ContentType = "text/xml";
        request.ContentLength = data.Length;
        System.IO.Stream stream = request.GetRequestStream();
        // Send the data.
        stream.Write(data, 0, data.Length);
        stream.Close();
        // Get the response.
        System.Net.WebResponse response = request.GetResponse();
        // Get the stream containing content returned by the server.
        stream = response.GetResponseStream();
        // Open the stream using a StreamReader for easy access.
        System.IO.StreamReader reader = new System.IO.StreamReader(stream);
        // Read the content.
        string responseFromServer = reader.ReadToEnd();
        // Clean up the streams.
        reader.Close();
        stream.Close();
        response.Close();
        Response.ContentType = "text/xml";
        MatchCollection result = Regex.Matches(responseFromServer, "<c o=\"([^\"]*)\" l=\"([^\"]*)\" s=\"([^\"]*)\">([^<]*)</c>");
        if (result != null && result.Count > 0)
            Response.Write(result[0].Value);
    }
    Response.Write("Failed");
}

Ответы [ 3 ]

1 голос
/ 25 августа 2011

Вам нужно написать себе ASP-версию включенного PHP-файла на стороне сервера. По сути, серверный компонент передает запрос в Google или использует проверку орфографии PHP. Поскольку вам не нужно конвертировать всю библиотеку Pspell, я бы порекомендовал просто перевести вызов на сайт проверки орфографии Google.

т.е. Создайте страницу ASPX и добавьте к ней следующий код

<%@ Import Namespace="System.Xml" %>
<script language="C#" runat="server">
public void Page_Load(Object src, EventArgs e)
{
    var str = Request["str"];
    if (str != null)
    {
        var url = "https://www.google.com";
        var path = "/tbproxy/spell?lang=en&hl=en";

        // setup XML request
        var xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>";
        xml += "<spellrequest textalreadyclipped=\"0\" ignoredups=\"0\" ignoredigits=\"1\" ignoreallcaps=\"1\">";
        xml += "<text>" + str + "</text></spellrequest>";
        ASCIIEncoding encoding = new ASCIIEncoding();
        byte[] data = encoding.GetBytes(xml);

        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url + path);
        request.Method = "POST";
        request.ContentType = "text/xml";
        request.ContentLength = data.Length;
        System.IO.Stream stream = request.GetRequestStream();

        // Send the data.
        stream.Write(data, 0, data.Length);
        stream.Close();

        // Get the response.
        System.Net.WebResponse response = request.GetResponse();

        // Get the stream containing content returned by the server.
        stream = response.GetResponseStream();

        // Open the stream using a StreamReader for easy access.
        System.IO.StreamReader reader = new System.IO.StreamReader(stream);

        // Read the content.
        string responseFromServer = reader.ReadToEnd();

        // Clean up the streams.
        reader.Close();
        stream.Close();
        response.Close();

        Response.ContentType = "text/xml";
        MatchCollection result = Regex.Matches(responseFromServer, "<c o=\"([^\"]*)\" l=\"([^\"]*)\" s=\"([^\"]*)\">([^<]*)</c>");
        if (result != null && result.Count > 0)
            Response.Write(result[0].Value);
    }
    Response.Write("Failed");
}
</script>

Затем измените вызов в js, чтобы он вызывал ваш новый файл aspx, а не checkpslling.php

1 голос
/ 08 марта 2012

Возможно, вам будет немного поздно, но для тех, кто пытается решить эту проблему, Джек Янг создал ASP-реализацию checkpelling.php, которую можно найти по адресу

https://github.com/jackmyang/jQuery-Spell-Checker-for-ASP.NET

0 голосов
/ 19 августа 2011

Плагин выполняет только код на стороне клиента.Вам необходимо указать URL-адрес вашего сценария ASP.

Прочитать документацию .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...