如何从Ajax调用的数据? [英] How to get data from ajax call?

查看:79
本文介绍了如何从Ajax调用的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过跨域获得来自AJAX调用数据。 这里是code

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

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

在函数结束时,x变量是不确定的,但中完成的事件值是正确的。 请问有人能帮助我或告诉什么是错在这code?

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?

推荐答案

这是因为你的AJAX请求异步完成。这意味着你的code中的其余部分将不会等待你的回应是准备继续。

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:

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

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

这篇关于如何从Ajax调用的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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