1

これが私がこれまでに持っているものです:

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

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

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

DOM に挿入される前に、Ajax 応答を取得して変更するにはどうすればよいですか? 以前は、ajaxCompleteインジェクション直後に DOM をバインドして変更していましたが、代わりに応答を変更したいと考えています。Ajax 応答で要素を見つけて、それらを使用して DOM を変更することはあまり意味がないと思います。を関数に送信しxhr.responseTextて、ボディの残りの部分に変更を再適用しないようにします。ボディの残りの部分は、Ajax 呼び出しの時点で既に変更されています。また、xhr.responseTextこれに使用するよりも良いものはありますか?仕事に行けなかっxhr.responseHTMLた。

編集:現在、単純なテスト Ajax 呼び出しを使用して MVC 部分ビューを返しています。

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

2 に答える 2

2

あなたの要件を正しく理解している場合、それらは次のとおりです。

  • 非同期 HTTP リクエストを作成して HTML を取得する
  • dataValModify() 関数を使用して、返された HTML を変更します。
  • ID 'ajaxTest' を使用して、変更した HTML を要素に挿入します。

もしそうなら、現在使用しているものよりも低レベルの ajax 呼び出しを行う必要があるように思えます。$(elem).load()

基本的に、への呼び出し.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);
  }
});
于 2011-08-12T14:37:56.807 に答える
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/

于 2011-08-12T13:53:15.100 に答える