当数据包含连续的问号时,无法理解的jQuery $ .ajax()行为 [英] Uncomprehensible jQuery $.ajax() behavior when data contains consecutive question marks

查看:71
本文介绍了当数据包含连续的问号时,无法理解的jQuery $ .ajax()行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望这很清楚,我已经浪费了很多精力来试图解决这个问题,所以我可能没有多少留下来写一个完美的问题。此外,这可能需要进入一个jQuery错误报告,但我宁愿先在这里发布,因为我是一个相对的JavaScript新手,所以也许我做错了...

I hope this is clear enough, I have wasted a lot of my energy trying to pin this problem down, so I may not have much left for writing a perfect question. Besides, this might have to go into a jQuery bug report, but I'd rather post it here first as I'm a relative JavaScript novice, so maybe I did something wrong...

我创建了以下代码片段来重现它。它使用PHP将收到的数据回显给浏览器,虽然它可以在没有任何PHP的情况下工作。

I created the following piece of code to reproduce it. It uses PHP to echo back the received data to the browser, although it might be able to work without any PHP.

问题可以在Firefox 4和Chrome 10中重现你需要控制台来看看发生了什么。

The problem can be reproduced in Firefox 4 and Chrome 10. You'll need the console to see what's happening.

这是代码:

<?
$input = file_get_contents('php://input');
if (isset($input) and !empty($input)) {
    echo $input;
    die();
}

?>

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
        <script>
            $(function(){
                var jsonData = {
                    "something":"??"
                };
                jsonData = JSON.stringify(jsonData);
                var onSuccess = function(data){
                    console.log("Ajax Success!");
                    console.log(data);
                }
                var onError = function(jqXHR, textStatus, errorThrown){
                    console.log("Ajax Error: "+textStatus);
                    console.log("More info:");
                    console.log(errorThrown);           
                    console.log(jqXHR);         
                }
                console.log("Now sending this: "+jsonData+" through Ajax...");
                var ajaxCmd = {
                    "url"       : "test.php", 
                    "dataType": "json",
                    "type"  : "POST",
                    "async" : false,
                    "error"     : onError,
                    "success"   : onSuccess,
                    "data"  : jsonData
                };
                $.ajax(ajaxCmd);
            });
        </script>
    </head>
    <body>
        <pre>Check your JavaScript console...</pre>
    </body>
</html>

加载时,会抛出一些明显不相关的解析错误或异常(取决于浏览器)。应该发送的json是{something:??}但是如果你在Firebug的网络选项卡(或Chrome等价物)中检查它,你会看到??正在被一些jQuery字符串取代,它看起来像:
jQuery152026845051744021475_1303152126170

When loaded, it throws some apparently unrelated parse error or exception (depending on the browser). The json that should be sent is {"something":"??"} but if you inspect it in the network tab of Firebug (or the Chrome equivalent) you'll see that "??" is being replaced by some jQuery string which looks like: jQuery152026845051744021475_1303152126170

这就是服务器收到的。

只有在发送的JSON对象内的值字段中有两个或多个连续的问号时才会出现此问题,即使其中有其他字母也是如此。有一个问号似乎有效。将dataType更改为text也可以解决此问题。但是我需要所有这些功能!

This problem only happens when there are two or more consecutive question marks in the value field inside the sent JSON object, even if there are other letters in there. With one question mark it seems to work. Also changing "dataType" to "text" fixes this. But I need all these features!

如果你注释掉jsonData = JSON.stringify(jsonData);或$ .ajax(ajaxCmd);错误也奇迹般地消失。

If you comment out "jsonData = JSON.stringify(jsonData);" or "$.ajax(ajaxCmd);" the errors also miraculously disappear.

更多信息:

Chrome控制台输出:

Chrome console output:

test.php:21Now sending this: {"something":"??"} through Ajax...
jquery.min.js:16Uncaught SyntaxError: Unexpected token :
test.php:16Ajax Error: parsererror
test.php:17More info:
test.php:18jQuery15206220591682940722_1303153398797 was not called
test.php:19
Object

Firefox Firebug输出:

Firefox Firebug output:

Now sending this: {"something":"??"} through Ajax...
Ajax Error: parsererror
More info:
jQuery15206494160738701454_1303153492631 was not called
Object { readyState=4, responseText="{"something":"jQuery152...8701454_1303153492631"}", more...}
invalid label
{"something":"jQuery15206494160738701454_1303153492631"}


推荐答案

如果你不是将数据值格式化为有效的HTML查询戒指,你不应该预先字符串化。正如您所指出的,如果您不调用JSON.stringify(),那么它可以工作。这是因为库已经知道为你处理它。

If you're not going to format the "data" value as a valid HTML query string, you shouldn't pre-stringify it. As you noted, if you don't call "JSON.stringify()" then it works. That's because the library already knows to handle that for you.

现在,如果你想将你的JSON字符串作为参数本身发送到服务器端代码,希望解码一些JSON,然后您需要将其设置为参数:

Now, if you want to send your JSON string as a parameter itself to server side code that expects to decode some JSON, then you need to set it up as a parameter:

    $.ajax(url, {
      // ...
      data: { jsonParam: jsonData },
      // ...
    });

现在您的服务器将看到一个带有名为jsonParam的参数的HTTP请求,其值将是你的JSON字符串字符串。

Now your server will see an HTTP request with a parameter called "jsonParam", and its value will be your JSON-stringified string.

这篇关于当数据包含连续的问号时,无法理解的jQuery $ .ajax()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆