如何从Ajax调用的数据?数据、Ajax

由网友(知足,才能常乐°)分享简介:我想通过跨域获得来自AJAX调用数据。这里是code I am trying to get data from ajax call by cross domain.Here is codefunction GetMaxWULen() {var x;$.ajax({url : url,method : 'PO...

我想通过跨域获得来自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/

阅读全文

相关推荐

最新文章