jquery $.ajax 调用成功但不返回任何内容。 (jsonp)
$(document).ready(function() {
$('#button').click(function() {
try {
var json = $.ajax({url : 'http://www.example.com/experimental/service.php', type : 'jsonp', success : function() {alert('success')}});
alert(json);
} catch(err) {
alert(err.description)
}
var sjson = JSON.stringify(json);
$('#display').html(sjson);
})
})
按下按钮后,我会收到一条警告消息,显示“成功”,还有一条显示未定义,指的是 ajax 调用没有返回任何内容。我检查了 firebug 'net' 选项卡,确实我从服务器“jsonp1272724228884( {} );”得到了成功的响应有什么想法吗?
$(document).ready(function() {
$('#button').click(function() {
try {
var json = $.ajax({url : 'http://www.example.com/experimental/service.php', type : 'jsonp', success : function() {alert('success')}});
alert(json);
} catch(err) {
alert(err.description)
}
var sjson = JSON.stringify(json);
$('#display').html(sjson);
})
})
After a button is pressed I get an alert message that says "success" and also one that says undefined, referring to the fact that nothing was returned from the ajax call. I checked the firebug 'net' tab and indeed i get a succesful response from the server of "jsonp1272724228884( {} );" Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为
alert(json);
显示未定义,因为它在收到响应之前运行。请记住,“ajax”是“异步”的,因此警报将在您的
json
值有机会被赋值之前继续执行。此外,即使它确实有效,您的
json
变量也只会引用生成的XMLHttpRequest
对象。如果您想访问数据本身,则需要在回调中执行此操作。编辑:
还有一个您可以分配的
error:
回调。如果服务器返回错误代码,则回调将执行。我认为这就是您打算用 try/catch 复制的内容。I would image that
alert(json);
is showing undefined because it is running before the response is received.Remember that 'ajax' is 'asynchronous', so that alert will go ahead and execute before your
json
value has a chance to be assigned a value.Furthermore, even if it did work, your
json
variable would simply reference theXMLHttpRequest
object that was made. If you want to access the data itself, you need to do so in the callback.EDIT:
There's also an
error:
callback that you can assign. The callback will execute if the server returns an error code. I assume that is what you intended to replicate with your try/catch.如果您想在进行ajax回调后立即使用结果,则必须设置ajax调用的
async:false
属性以使其同步。由于这通常不是您想要做的,因此您可能应该以不同的(异步)方式处理响应。If you want to use the result right after making the ajax callback, you have to set the
async : false
attribute of ajax call to make it synchronous. As this is usually not what you want to do, you should probably process the response in a different (asynchronous) way.