jquery $.ajax call succeeds but returns nothing. (jsonp)

笑着哭i 提交于 2019-12-25 03:01:45

问题


$(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?


回答1:


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 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);
              }
});

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.




回答2:


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.



来源:https://stackoverflow.com/questions/2750393/jquery-ajax-call-succeeds-but-returns-nothing-jsonp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!