jQuery $ .ajax调用成功,但不返回任何内容. (jsonp) [英] jquery $.ajax call succeeds but returns nothing. (jsonp)

查看:412
本文介绍了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({});"的成功响应.有任何想法吗?

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?

推荐答案

我会想象alert(json);显示为未定义,因为它在接收响应之前正在运行.

I would image that alert(json); is showing undefined because it is running before the response is received.

请记住,"ajax"是异步的",因此警报将继续执行,并在您的json值有机会被分配值之前执行.

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.

此外,即使它确实起作用,您的json变量也只会引用所创建的XMLHttpRequest对象.如果要访问数据本身,则需要在回调中进行访问.

Furthermore, even if it did work, your json variable would simply reference the XMLHttpRequest object that was made. If you want to access the data itself, you need to do so in the callback.

var json;

$.ajax({
    url : 'http://www.example.com/experimental/service.php', 
    type : 'jsonp', 
    success : function(data) {
                  alert('success');
                  json = data;
                  alert(json);
              }
});


还有一个您可以分配的error:回调.如果服务器返回错误代码,则将执行回调.我认为这就是您打算通过try/catch复制的内容.

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.

这篇关于jQuery $ .ajax调用成功,但不返回任何内容. (jsonp)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆