Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

javascript - Is it posible to use ajax respone outside of it?

Any way of using the data_response outside the $.post()?

This is part of the code I use:

$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        var response = data_response; //I need to access this variable outside of $.post()
    }
}, "json");

console.log(response); //response is not defined, is what I get for now

UPDATE

Is there no way of getting that response available globally?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No; $.post executes asynchronously, so when you call console.log, the AJAX request is still running and hasn't yet yielded a response. This is the purpose of the callback function: to provide code to be run after the request has completed. If you move console.log into the callback function, it should work:

$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        var response = data_response; //I need to access this variable outside of $.post()
        console.log(response);
    }
}, "json");

Update: If you want the response data to be globally available, you can declare the variable in the global scope like so:

var response = null;
$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        response = data_response;
        console.log(response);
    }
}, "json");

Of course, the only context in which you can be sure that response has actually been populated with a value is in the callback function supplied to $.post after the line response = data_response;. If you want to use it at any other stage in the script then you'll have to check its value first; something like this:

if (response !== null)
{
    console.log(response);
}

Just be aware that this code won't do anything if you put it straight after the $.post call; it'll only be useful if it's executed after the POST request has finished, in some other asynchronous callback (perhaps a UI interaction event of some kind).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...