从jquery get方法中传递数据 [英] pass data out from jquery get method

查看:86
本文介绍了从jquery get方法中传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

get方法中的警报正确返回值。但是,get方法之外的第二个alert中的transactionID仍然为空时?如何从get方法中正确地传递返回数据?

解决方案 $。get

code>是异步执行的,即它将请求发送到服务器并执行后面的行。
因此,外部警报将在服务器返回答复之前执行,并且当它执行时,它将执行 get 方法中的函数。



为了使用返回的值,将所有需要的代码放在 get 调用中,例如调用另一个函数,将transactionID作为参数传递给一个参数:

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

或者只是调用一个函数来使用它:

  $ .get('http://127.0.0.1/getId',null,function(data){
transactionID = data;
alert(transactionID );
doSomethingWithID();
});
函数doSomethingWithID()
{
//使用transationID的代码
}


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?

解决方案

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方法中传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆