0

我有以下问题:

$('#id').on('click', '.class', function(){
 // it is doing something and
 // executing AJAX request
 // with the data from request it is doing something
} // this is onclick handler

稍后在代码中我也需要执行它,执行后我需要运行另一个函数,这取决于 this 的 ajax 执行onclick handler,所以我正在做这样的事情

$('#id .class').click();
anotherFunction();

它不工作。这个问题是可以理解的,因为ajax请求还没有完成。

我尝试使用Deferred object的想法来实现正确的执行。

$.when( $('#id .class').click() ).then( anotherFunction() );

并使用带有回调的自动执行函数的想法:

(function(o, callback){
    $('#id .class').click()
})(null, anotherFunction() );

两种想法都失败了。

有什么方法可以在不修改anotherFunction()and的情况下实现预期的功能onclick function

4

1 回答 1

0

不确定我是否完全理解您的问题,但是是什么让您无法在相应的 $.ajax 响应方法中执行 onsuccess / onerror 代码?

$.ajax({
  type: 'POST',
  url: "your url",
  data: "your data",
  error: function(jqXHR, textStatus, errorThrown) { ... },
  success: function (data, textStatus, jqXHR) { ... }
});

另外,为什么不将 ajax 执行部分放到一个自己的函数中,然后从事件处理程序和其他所有地方调用它,就像这样?

function ajaxMe(onerror, onsuccess)
{
    $.ajax({
      type: 'POST',
      url: "your url",
      data: "your data",
      error: function(jqXHR, textStatus, errorThrown) { onerror(...) },
      success: function (data, textStatus, jqXHR) { onsuccess(...) }
    });
}
于 2012-11-18T15:35:59.357 回答