Update:
Looks like a bug in jQuery to me It is a bug in jQuery, specifically bug #8417 http://bugs.jquery.com/ticket/8417, which was reported about five weeks ago, closed erroneously, then reopened and there's now a pull request with a fix pending; hopefully the fix will make a future version.
解决方法如下,但首先:此代码单独复制它:
jQuery(function($) {
$('#theButton').click(function go() {
var data = { "Name": "test??", "testDesc": "description"};
$.ajax({
url: "/icece5",
data: JSON.stringify(data),
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false
});
});
});
实时复制 http://jsbin.com/icece5/4
虽然我们在 jsbin.com 上看不到 POST 的结果,但我们不在乎,因为这就是我们要做的sending到我们担心的服务器。如果我发送该请求并在 Chrome 的开发工具中查看该请求,我会清楚地看到数据被下面描述的 JSON-P 回调名称损坏。
有趣的是,如果我们不告诉 jQuery 我们期待从服务器返回 JSON(请注意注释掉的行),则不会发生这种情况:
jQuery(function($) {
$('#theButton').click(function go() {
var data = { "Name": "test??", "testDesc": "description"};
$.ajax({
url: "/icece5",
data: JSON.stringify(data),
type: "POST",
contentType: "application/json; charset=utf-8",
//dataType: "json",
cache: false
});
});
});
实时复制 http://jsbin.com/icece5/5
我没有想到,返回的数据类型不应该影响它对我们发送的数据的处理。但它确实需要一个解决方法:
解决方法
var data = { "Name": "test??", "testDesc": "testdesc??"};
$.ajax({
url: "submit.aspx/SubmitData",
data: JSON.stringify(data),
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "text", // <== Tell jQuery you expect plain text
cache: false
}).success(function (data) {
data = jQuery.parseJSON(data); // <=== Then parse it yourself
});
Recommend putting together a test case on jsFiddle.net and reporting it http://bugs.jquery.com/newticket to the jQuery team, since you're the person with the real-life problem with it. If it's really a bug, they'll fix it; if not, I'd be interested to know why not...
原答案:
您引用的代码正在执行POST
JSON 编码数据,但是您提到的字符串(jQuery151023383707909744822_1301931324827
等)是 jQuery“expando”(通过获取 jQuery 版本并向其添加随机值在运行时确定)加上_
加上纪元值。 jQuery 以该形式创建字符串作为 JSON-P 回调函数的默认名称,如下所示:
jQuery-1.5.1.js 的第 1,326-1,329 行:
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
以及(第 7,029-7,035 行):
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
所以我的猜测是,您引用的代码不是生成这些值的代码,而是您有其他代码使用它们。
JSON-P 回调的名称将替换?
如果您使用 JSON-P 进行请求,则在请求的 URL 中。我没想到它会在你的data.
我会审查你的使用情况ajaxSettings
等等。如果您切换到未缩小的版本进行调试,您还可以在您使用的任何调试器中设置断点(你用了一个,对吧?没有理由不这样做 http://blog.niftysnippets.org/2011/03/no-excuse.html)在第 7,033 行(正在创建这些字符串的地方),然后找出代码的哪一部分触发了它。