pass data out from jquery get method

2019-09-01 09:32发布

问题:

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
}


标签: jquery get