10

我想在呈现 ajax 响应后执行一段 javascript。javascript 函数是在 ajax 请求期间动态生成的,并且在 ajax 响应中。“完成”和“成功”事件不做这项工作。我在 Firebug 控制台中检查了 ajax 请求,并且在执行完整回调时没有呈现响应。

Does not work:

      function reloadForm() {
        jQuery.ajax({
          url: "<generate_form_url>",
          type: "GET",
          complete: custom_function_with_js_in_response()
        });
      };

ajaxComplete 完成这项工作,但它为页面上的所有 ajax 调用执行。我想避免这种情况。有没有可能的解决方案?

$('#link_form').ajaxComplete(function() {
  custom_function_with_js_in_response();
});
4

4 回答 4

14

你也可以使用 $.ajax(..).done(do_things_here());

$(document).ready(function() {

    $('#obj').click(function() {

    $.ajax({
        url: "<url>"
    }).done(function() {
      do_something_here();
    });
});

});

还是有其他方法

$(document).ready(function() {

    $('#obj').click(function() {

    $.ajax({
        url: "<url>",
        success: function(data){
          do_something_with(data);
        }
    })
});

});

请利用此引擎分享您的问题并尝试解决方案。它非常有效。

http://jsfiddle.net/qTDAv/7/(PS:这包含一个示例尝试)

希望有所帮助

于 2012-09-24T11:46:11.307 回答
1

检查(并在需要时推迟调用)并执行回调函数的存在可能会起作用:

// undefine the function before the AJAX call
// replace myFunc with the name of the function to be executed on complete()
myFunc = null; 

$.ajax({
    ...
    complete: function() {
       runCompleteCallback(myFunc);
    },
    ...
});

function runCompleteCallback(_func) {
    if(typeof _func == 'function') {
        return _func();
    }
    setTimeout(function() {
        runCompleteCallback(_func);
    }, 100);
}
于 2012-09-24T11:16:33.253 回答
0

没有代码就帮不上什么忙。作为JQuery ajax 完整页面的一般示例

$('.log').ajaxComplete(function(e, xhr, settings) {
    if (settings.url == 'ajax/test.html') {
        $(this).text('Triggered ajaxComplete handler. The result is ' +
                 xhr.responseHTML);
    }
});

在 ajaxComplete 中,您可以决定过滤要为其编写代码的 URL。

于 2012-09-24T10:02:46.760 回答
0

尝试在没有()ajax 选项的情况下指定函数名称:

function reloadForm() {
        jQuery.ajax({
          url: "<generate_form_url>",
          type: "GET",
          complete: custom_function_with_js_in_response
        });
      };
于 2012-09-24T10:50:29.207 回答