如果字符串中有空白,jquery.load()将不返回任何内容


jquery .load() returns nothing if the string has a whitespace

我对jquery函数.load()有问题我想从php中的输入字段中获取值,但如果在字段中输入空白,则一无所获

这是我的短代码html

 <!DOCTYPE html>
    <html>
        <head>
            <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
        </head>
        <body>
            <input type="text" onkeyup="$('#result').load('test.php?str='+$(this).val()).hide().fadeIn();" />
            <div id="result" ></div>
        </body>
    </html>

和test.php

<?php
echo $_GET[str];

如果该字符串中有空格,则后一个块将被视为返回HTML的选择器。如果选择器与任何内容都不匹配,则不返回任何内容。

您需要使用encodeURIComponent()对参数进行编码。这将确保它不会以文字空间结束,因为它们将使用%20进行编码。

您应该在$(this).val()上使用encodeURIComponent

单独编写javascript

$('input[type=text]').keyup(function() {
    $('#result').load('test.php?str=' + encodeURIComponent($.trim($(this).val())) ).hide().fadeIn();
});