javascript 如何从ajax调用中获取数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19680854/
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 16:27:48  来源:igfitidea点击:

How to get data from ajax call?

javascriptjqueryajax

提问by dawid

I am trying to get data from ajax call by cross domain. Here is code

我正在尝试通过跨域从 ajax 调用中获取数据。这是代码

function GetMaxWULen() {
var x;
$.ajax({
    url : url,
    method : 'POST',
    jsonp : "callback",
    async : false,
    data : {
        Function : "GetMaxWULen",
        Authorization : Base64.encode(login + ":" + token),
        WuType : $("#ddlWUType").val()
    },
    dataType : 'jsonp',
    crossDomain : true,
    error : function(request, status, error) {
        alert('nie uda?o sie');
        alert(error);
    }
}).done(function(result) {
    console.log('done result');
    x = result;
    console.log(x);
});
console.log('function end');
console.log(x);}

At the end of the function, x variable is undefined but in done event value is correct. Could anyone can help me or tell what is wrong in this code?

在函数结束时, x 变量未定义但在 done 事件值是正确的。任何人都可以帮助我或告诉我这段代码有什么问题吗?

回答by Guilherme Sehn

This happens because your AJAX request is done asynchronously. It means the rest of your code won't wait your response be ready to continue.

发生这种情况是因为您的 AJAX 请求是异步完成的。这意味着您的其余代码不会等待您的响应准备好继续。

If you need to use the data returned from AJAX outside your function, you might want to create a parameter to serve as a callback when the response is ready. For example:

如果您需要在函数外使用从 AJAX 返回的数据,您可能需要创建一个参数以在响应准备好时用作回调。例如:

function yourFunction(callback) {
    $.ajax({
        /* your options here */
    }).done(function(result) {
        /* do something with the result here */
        callback(result); // invokes the callback function passed as parameter
    });
}

And then call it:

然后调用它:

yourFunction(function(result) {
    console.log('Result: ', result);
});

Fiddle: http://jsfiddle.net/9duek/

小提琴:http: //jsfiddle.net/9duek/

回答by Mr.GT

try

尝试

$.ajax({
    url : url,
    method : 'POST',
    jsonp : "callback",
    async : false,
    data : {
        Function : "GetMaxWULen",
        Authorization : Base64.encode(login + ":" + token),
        WuType : $("#ddlWUType").val()
    },
    dataType : 'jsonp',
    crossDomain : true,
    error : function(request, status, error) {
        alert('nie uda?o sie');
        alert(error);
    }
}).success(function(result) {
    var datareturned = result.d;
    console.log('done' +  datareturned);
    x = datareturned;
    console.log(x);
});