pass data out from jquery get method

故事扮演 提交于 2019-12-25 02:34:38

问题


var transactionID;
$.get('http://127.0.0.1/getId', null,function(data) {
    transactionID = data;
    alert(transactionID);
});
alert(transactionID);

The alert inside the get method returns value correctly. However, when the transactionID in the 2nd alert outside of the get method is still null? How to correctly pass out the return data from the get method?


回答1:


The $.get is executed asynchronously, i.e. it sends the request to the server and executes the lines after it. So the alert outside will be executed before the server returns the reply, and when it does it will execute the function in the get method.

In order to use the returned value, place any needed code inside the get call, for example call another function passing it the transactionID as an argument:

var transactionID;
$.get('http://127.0.0.1/getId', null,function(data) {
    transactionID = data;
    alert(transactionID);
    doSomethingWithID(transactionID);
});

Or just call a function the uses it:

$.get('http://127.0.0.1/getId', null,function(data) {
    transactionID = data;
    alert(transactionID);
    doSomethingWithID();
});
function doSomethingWithID()
{
  // code that uses transationID
}


来源:https://stackoverflow.com/questions/22529787/pass-data-out-from-jquery-get-method

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