我将用户名和密码作为请求参数发送到 AJAX 中的服务器并尝试显示响应消息。但无法显示响应消息。在 fiddler 中,它正在显示响应消息。但是在浏览器屏幕上它没有显示。请有人帮我找出我错的地方或需要改变任何东西..
我是这样写的——
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://test.xyz.com/login",
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { username: "abc", password: "1234" },
dataType: "JSONP",
jsonpCallback: 'jsonCallback',
async: false,
success: function (resdata) {
alert(resdata);
},
error: function (result, status, err) {
alert(result.responseText);
alert(status.responseText);
alert(err.Message);
}
});
});
});
最佳答案
TL;DR:我想问题出在您代码的服务器端(我们还不知道)。
起初:我不知道为什么它对你失败。我已经获取了您的代码并针对公共(public)可用的 JSONP API 运行它,该 API 返回您系统的当前 IP 并且它有效。
请尝试使用以下 URL:http://ip.jsontest.com/
.
所以很可能,服务器没有对 JSONP 请求返回正确的响应。查看开发人员工具中的网络选项卡。使用您当前的代码,服务器的答案应该是这样的:
jsonCallback({'someResponseKeys': 'someResponseValue'});
注意:标题应包含
Content-Type:application/javascript
!顺便说一句,即使这暂时不能解决您的问题 - 这里有一些调整,我想给您一些建议:
async
为假,在 jQuery.ajax() 的文档中说:Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation.
jsonpCallback
,因为 jQuery 将生成和处理(使用 success
函数为您随机生成一个。引用自文档:This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
所以这是我的代码:
$(document).ready(function () {
$("#btnCity").click(function () {
$.ajax({
type: "POST",
url: "http://ip.jsontest.com/",
crossDomain: true,
data: { username: "abc", password: "1234" },
dataType: "JSONP",
success: function (resdata) {
console.log("success", resdata);
},
error: function (result, status, err) {
console.log("error", result.responseText);
console.log("error", status.responseText);
console.log("error", err.Message);
}
});
});
});
一个工作example can be found here .
另一种解决方案,如 Yonatan Ayalon 建议的那样,可以使用预定义函数完成,然后设置
jsonpCallback
显式地指向应该调用的函数。
关于ajax - 如何在警报中显示 AJAX 响应消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24982226/