发送带有空格的 jQuery 获取


Send Get with jQuery with spaces

我在使用 jQuery 的字数统计方面遇到问题。一旦我单击空格,该方法就会停止。

.HTML:

<textarea id="essay_content_area" name="essay_content" onkeydown="words();"></textarea>
<td>Number of words: <div id="othman"></div></td>

j查询:

function words(content)
{
    var f = $("#essay_content_area").val()
    $('#othman').load('wordcount.php?content='+f);
}

PHP文件:

if(isset($_GET['content']))
{
        echo $_GET['content']; // if it works I will send this variable to a function to calculate the words 
}

脚本显示内容,直到我单击空格。 有什么建议吗?

在将

值作为 GET 参数的值发送到 PHP 脚本之前,您需要对值进行 url 编码。 考虑一下:

function words(content)
{
    var f = $("#essay_content_area").val()
    $('#othman').load('wordcount.php?content=' + encodeURIComponent(f));
}

你不需要 php 来计算你可以使用 JS 的单词,如下所示:

function words(content)
{
   // Get number of words.
   var words = content.split(" ").length;
}

您需要在发送变量之前对其进行 url 编码(空格不是有效的 url 字符):

function words(content)
{
    var f = encodeURIComponent($("#essay_content_area").val());
    $('#othman').load('wordcount.php?content='+f);
}