javascript - 理解 jquery 回调

标签 javascript jquery callback

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

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

alert() 返回正确的值,并且按预期运行。但是,我不明白如何将 arrayData[2] 中的值传递或返回到我程序的其他部分(而且我所做的尝试都没有奏效)。

我已经通读了 jquery help以及许多 SO 问题和答案,但我不明白回调是如何工作的。

在这种情况下,我希望 arrayOfValues[2] 可以被我的主程序访问。

最佳答案

$.post() 是异步(非阻塞)调用,这意味着该函数立即返回(不等待服务器响应)并执行下一个 javascript 代码。 当来自服务器的响应到达时,您的回调函数被调用,响应...

比方说,您想在一个 div 中显示内容:

$.post('url.php', {}, function(content) {
  $('#div_id').html(content);
});

// or shorter:
$('#div_id').load('url.php', {});

或者您可以拥有一个具有某些逻辑的对象并将对象的方法注册为回调:

function MyHandler(msgElement) {
  var sum = 0;
  this.onSuccess = function(content) {
    sum = sum + content[0];
    if (sum > 100) {
      msgElement.html('Sum has reached 100 !');
    }
  };
  this.otherMethod = function() {
    alert('Current sum is:' + sum);
  };
}

var handler = new MyHandler($('#my_div'));

// do the request
$.post('url.php', {}, handler.onSuccess, 'json');

// you can call any method of handler object using global variable handler
// or passing a reference (handler object) to any other object
// notice, if you call this method immediately after sending the request,
// the sum var is likely to be 0, as the response has not arrived yet...
handler.otherMethod();

基本上,您有很多选择。因此,如果您需要更多信息,请具体说明您想要做什么响应...

关于javascript - 理解 jquery 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4709035/

相关文章:

javascript - Google JavaScript API v3 - 街景服务 - 关闭建筑内部

javascript - 分配动态模板

jquery - 如何使用 .on 定位使用 ajax 加载的元素

javascript - 如何打破 JavaScript 中的回调链?

javascript - 使用 Create-React-App 时,Webpack 需要抛出“目标容器不是 DOM 元素?”

Javascript if 和 else 同时运行

javascript - 如何向数组中的 img 元素添加类?

Jquery slider : make part of it available?

jQuery - 从外部脚本 Hook $.ajax 调用

java - 释放 JNI 数组