【发布时间】:2014-07-27 09:46:50
【问题描述】:
我通过两种方式向服务发出请求
1) 通过 XMLHTTPRequest->不工作
说 --> JSON.parse 第 1 行 col1 中的数据意外结束
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function sign() {
var logincredentials = JSON.stringify({
"username": "_username",
"password": "_passsword"
});
var url = serviceurl;
var xhr = createCORSRequest('POST', url);
if (!xhr) {
alert('CORS not supported');
}
xhr.onload = function () {
alert("success : ");
};
xhr.onerror = function () {
alert("failed : ");
};
xhr.setRequestHeader('Content-Type', 'application/jsonrequest; charset=UTF-8');
xhr.send(logincredentials);
}
2) JQuery Ajax 工作正常
function signJQ() {
var userData = JSON.stringify({
"username": "_username",
"password": "_password"
});
$.ajax({
type:"POST",
url:"serviceurl",
contentType: "application/json",
dataType: "json",
data:userData,
success: function(data) {
alert("success: " + JSON.stringify(data));
},
error: function(data) {
alert("Failed: " + JSON.stringify(data));
}
});
}
这两种情况可能有什么不同?
【问题讨论】:
-
你定义
createCORSRequest函数了吗? -
你试过哪个浏览器?
-
据我所知,xhr 有
onreadystatechange。所以用它代替onload和onerror。哦,我错了,xhr2 同时适用于 onload 和 onerror。 -
你可以试试这个:
xhr.send("json="+logincredentials);
标签: javascript jquery ajax cors