我很难过如何解决/诊断ajax / jquery错误。
这是我的功能:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
我收到此错误:
答案 0 :(得分:2)
jQuery不支持使用POST和jsonp,原因很简单:当你向DOM注入一个<script>
标签时(这是jQuery在你使用jsonp时所做的),浏览器会发送对远程端点的GET请求,该请求已在此标记的src
属性中引用。
所以基本上你需要使用GET代替:
type: "GET"
此外,由于数据是作为查询字符串参数发送的,因此您应删除内容类型:
contentType: "application/json",
并且不要JSON.stringify
数据。
以下是完整的例子:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
当然,只有远程端点支持JSONP和GET动词时,这才有效。
就我个人而言,我建议使用CORS而不是JSONP,因为它会为您提供更多选择。在这种情况下,您将能够使用POST。请参阅以下资料,因为您似乎在服务器上使用ASP.NET Web API并尝试进行跨域AJAX调用:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api