Is it posible to use ajax respone outside of it?

南笙酒味 提交于 2019-12-18 05:22:23

问题


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?


回答1:


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).




回答2:


Just declare the variable outside of the callback so it is scoped to a part of the code that you can reach it from:

var response;

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

console.log(response); //response is now defined - It won't be populated yet though.

As pointed out in the code above, although response will be defined, it won't be populated by the time you call console.log, however if you access the variable at some point after the callback has fired, it will be populated.

If you go down this route, you probably want to make use of a module pattern or closure to avoid putting the response variable in the global scope (you probably want to do this anyway in fairness)

Crockford's Module pattern: http://www.yuiblog.com/blog/2007/06/12/module-pattern/




回答3:


You can use a a variable, and check for done() anywhere in your script, if it's done it will execute immediately, if not it will execute once the ajax call is done.

var XHR = $.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        // do somehing with data_response
    }
}, "json");


function doSomethingElse() {
    XHR.done(function(response) {
        console.log(response);
    });
}



回答4:


If you need to use the response outside of $.post() and you need to be sure that this value is populated right after the $.post() call you could try to make the "POST" call in a synchronous manner. This cannot be made with $.post() but cand be made using $.ajax():

var returnedData = null;

$.ajax({
  type: 'POST',
  url: 'do.php', 
  data: { OP: "news_search", category: cat_id },
  success: function (response) {
            returnedData = response;
        },
  dataType: "text"
});

console.log(returnedData );



回答5:


I got it working like this:

var returnedData = {}; //Declaring Object var not just var
$.ajax({
type: 'POST',
url: 'do.php',
data: { OP: "news_search", category: cat_id },
success: function (response) {
returnedData.result1=response;  //Add response into the Object created outside the ajax
},
dataType: "json"
});
console.log(returnedData);//inside it you can get returnedData.result1


来源:https://stackoverflow.com/questions/10652887/is-it-posible-to-use-ajax-respone-outside-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!