javascript Jquery ajax不返回数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16286223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:04:22  来源:igfitidea点击:

Jquery ajax not returning data

javascriptjqueryajaxreturn

提问by Ramazan APAYDIN

Ajax does not turn back any data.

Ajax 不会返回任何数据。

http://jsfiddle.net/w67C4/

http://jsfiddle.net/w67C4/

$.ajax({
    dataType:'jsonp',
    url: url,
    async:false,
    success: function(data){
        getUsername = data.user.id;
    },
});

Returning data is null but required to return the userId

返回数据为空但需要返回userId

回答by Mehdi Karamosly

Your data is returned correctly :

您的数据已正确返回:

Object {user: Object, stat: "ok"}
stat: "ok"
user: Object
  ->id: "66956608@N06"
  ->username: Object
__proto__: Object

enter image description here

在此处输入图片说明

This is how you can process the results :

这是您处理结果的方式:

function foo() {
    return $.ajax(...);
}

foo().done(function(result) {
    // code depending on result
}).fail(function() {
    // an error occurred
});

function getUserId() {
    var url = "http://api.flickr.com/services/rest/?jsoncallback=?&api_key=fc6c52ed4f458bd9ee506912a860e466&method=flickr.urls.lookupUser&format=json&nojsoncallback=1&url=http://www.flickr.com/photos/flickr";
    var getUsername = null;

    return $.ajax({
        dataType: 'jsonp',
        url: url,
        async: false
    });
}

getUserId().done(function (result) {
    // Call the alert here..
    alert(result.user.id);
}).fail(function(err){
      alert('an error has occured :'+err.toString());
   });

回答by pala?н

You need to do this:

你需要这样做:

function getUserId() {
    var url = "http://api.flickr.com/services/rest/?jsoncallback=?&api_key=fc6c52ed4f458bd9ee506912a860e466&method=flickr.urls.lookupUser&format=json&nojsoncallback=1&url=http://www.flickr.com/photos/flickr";
    var getUsername = null;

    return $.ajax({
        dataType: 'jsonp',
        url: url,
        async: false
    });
}

getUserId().done(function (result) {
    // Call the alert here..
    alert(result.user.id);
});

FIDDLE

小提琴

回答by nikeaa

This is because the AJAX function is called asyncronously. This means that the URL is called, and while the processing is taking place, the javascript code continues executing and returns from your function. You can see this by putting an alert for getUsername inside of your success handler. At that point you can see that the data is actually being returned correctly.

这是因为 AJAX 函数被异步调用。这意味着 URL 被调用,并且在处理过程中,javascript 代码继续执行并从您的函数返回。您可以通过在成功处理程序中放置 getUsername 的警报来查看这一点。此时您可以看到数据实际上被正确返回。