簡體   English   中英

在呈現ajax響應后執行Javascript

[英]Execute Javascript after ajax response has been rendered

我想在渲染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();
});

你也可以使用$ .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 :這包含一個試用的樣本)

希望能有所幫助

檢查(並在需要時延遲調用)並執行回調函數的存在可能有效:

// 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);
}

沒有代碼就無濟於事。 作為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。

嘗試在ajax選項中指定不帶()函數名稱:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM