我希望这已经足够清楚了,我已经花了很多时间试图确定这个问题,所以我可能没有多少时间来写一个完美的问题了。此外,这可能必须进入 jQuery 错误报告,但我宁愿先在这里发布,因为我是一个相对的 JavaScript 新手,所以也许我做错了什么......
我创建了以下代码来重现它。它使用 PHP 将接收到的数据回显给浏览器,尽管它可能在没有任何 PHP 的情况下也能工作。
该问题可以在 Firefox 4 和 Chrome 10 中重现。您需要控制台才能查看发生了什么。
代码如下:
<?
$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
这就是服务器接收到的。
只有在发送的 JSON 对象内的 value 字段中有两个或多个连续问号时才会出现此问题,即使其中还有其他字母。一个问号,它似乎工作。将“dataType”更改为“text”也可以解决此问题。但我需要所有这些功能!
如果你注释掉“jsonData = JSON.stringify(jsonData);”或“$.ajax(ajaxCmd);”错误也奇迹般地消失了。
更多信息:
Chrome 控制台输出:
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 输出:
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"}
最佳答案
jQuery 在使用 jsonp
时使用 ??
作为回调函数的占位符。当它解析 Ajax 请求并找到双问号(或多个问号)时,它会自动假定您正在尝试使用 jsonp
。当您手动设置内容类型时,它会忽略问号。
所以,使用 contentType 来避免这个问题:
$.ajax(
url: "your-url.php",
dataType: "json", // what you expect the server to return
contentType: "application/json", // what you are sending
...
);
供引用:
jQuery Bugtracker: $.AJAX CHANGED THE POST CONTENT IF INCLUDE "??" (2 QUESTION MARK)
希望它能帮助其他人免于数小时的调试...
关于javascript - 数据包含连续问号时无法理解的 jQuery $.ajax() 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5707619/