理解jquery回调 [英] Understanding jquery callbacks

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

问题描述

我很难理解JavaScript回调应该如何工作。我使用以下代码从MySQL数据库获取值:

  $ .post(getResults.php,{x :100,y:200},
function(arrayOfValues){
alert(arrayOfValues [2])
},'json'

alert()返回正确的值,并按预期运作。但是,我不明白如何从 arrayData [2] 的值可以传递或返回到我的程序的其他部分(和我做的尝试没有工作) 。



我阅读过 jquery帮助和许多SO问题和答案,但我不明白回调的工作原理。



在这种情况下,我想要arrayOfValues [2]

$

  var foo; 



$ .post(getResults.php,{x:100,y:200},function(data){
foo = data;
},'json' );

响应数据将存储到 foo 变量。但是,请注意,这是一个异步回调函数,当HTTP响应到达时调用。请务必了解,在HTTP响应到达且回调函数已完成之前不能使用 foo 变量


I have difficulty understanding how a javascript callback should work. I am using the following code to get values from a MySQL database:

  $.post("getResults.php", { x: 100, y: 200},       
   function(arrayOfValues){  
      alert( arrayOfValues[2] )         
   }, 'json');

alert() returns the correct value, and is functioning as expected. However, I don't understand how the value from arrayData[2] can be passed or returned to other parts of my program (and attempts I've made have not worked).

I've read through the jquery help and numerous SO questions and answers but I don't understand how a callback works.

In this case, I want arrayOfValues[2] to be accessible by my main program.

解决方案

var foo;

$.post("getResults.php", { x: 100, y: 200 }, function(data) {  
    foo = data;       
}, 'json');

The response data will be stored into the foo variable. Note, however, that this is an asynchronous callback function which is called when the HTTP response arrives. It is important to understand that you cannot use the foo variable until that HTTP response has arrived and the callback function has finished.

这篇关于理解jquery回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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