pass data out from jquery get method

2019-09-01 09:09发布

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?

标签: jquery get
1条回答
趁早两清
2楼-- · 2019-09-01 09:47

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
}
查看更多
登录 后发表回答