2011-08-12 36 views
1

這是我到目前爲止有:如何在將Ajax響應注入到DOM之前操作它?

$(function() { 
    dataValModify('body'); 

    $('body').bind('ajaxSuccess', function (e, xhr, settings) { 
     dataValModify(xhr.responseText); 
    }); 
}); 

function dataValModify(elem) { 
    // Code to modify elements within the response. 
} 

我怎樣才能把Ajax響應,並修改它之前被注入到DOM?之前,我綁定了ajaxComplete並在注入後直接修改DOM,但是我想修改響應。我認爲在Ajax響應中查找元素並使用它們來修改DOM是沒有多大意義的。我將xhr.responseText發送到我的函數中,以便我不會將修改重新應用到正文的其餘部分,這些修改在Ajax調用時已經被修改。另外,有什麼比xhr.responseText更好的用於這個嗎?我無法獲得xhr.responseHTML的工作。

編輯:現在我只是用一個簡單的測試Ajax調用返回一個MVC局部視圖:

$('#ajaxTest').load('<MVC Route>') 

回答

2

如果我正確理解你的要求,它們是如下所示:

  • 發出一個異步HTTP請求來獲取一些HTML
  • 使用dataValModify()函數
  • 將修改HTML與ID你的元素修改返回的HTML:「ajaxTest」

如果是這樣那麼它聽起來像你對我需要做一個下級Ajax調用比您正在使用目前即$(elem).load()

什麼本質上的呼叫​​是$.get()的包裝,然後以$(elem).html(someContent)調用其中「somecontent寫入」是從HTTP請求的responseText的。

因此,如果你想之前它注入DOM修改響應,那麼你可以做類似如下的內容:

$.ajax({ 
    type: "GET", 
    url: "<MVC Route>", 
    dataType: "html", 
    success: function(jqXHR, textStatus, errorThrown){ 

    // Your HTTP call was successful but nothing else has happened with the response yet 
    // Therefore you can now do whatever you want with the it... 

    // First modify the HTML using the dataValModify function 
    // Assumption being that your function returns the modified HTML string 
    var myModifiedHTML = dataValModify(jqXHR.responseText); 

    // Inject the modified HTML 
    $('#ajaxTest').html(myModifiedHTML); 
    } 
}); 
+0

我明白了。我擔心可能是這種情況!問題是我正在開發一個框架,所以我不能強迫開發人員在必須修改HTML的情況下發出這樣的調用,它需要是「自動的」。我通過在'ajaxComplete'之後修改DOM來按原樣工作,但我不希望修改響應。謝謝您的回答! – Brandon

0

您可以使用ajaxComplete修改responseHTML本身。

$('body').ajaxComplete(function(e, xhr, settings) { 
     dataValModify(xhr.responseHTML); 
}); 

更新:我還沒有嘗試過,但它可能會幫助:

$.ajaxSetup({ 
    converters: { 
    "text html": function(textValue) { 
     if (valid(textValue)) { 
     // Some parsing logic here 
     return dataValModify(textValue); 
     } else { 
     // This will notify a parsererror for current request 
     throw exceptionObject; 
     } 
    } 
    } 
}); 

此處瞭解詳情:http://api.jquery.com/extending-ajax/

+0

在的'ajaxComplete'的HTML已經被注入的時間。另外,'xhr.responseHTML'在'ajaxSuccess'和'ajaxComplete'處都返回undefined。 – Brandon

+0

你可以發佈你的'ajax'調用代碼嗎? – Mrchief

+0

將其添加爲編輯。 – Brandon

相關問題