如何在将Ajax响应注入DOM之前对其进行操作?

时间:2011-08-12 13:48:45

标签: ajax jquery ajax-request

这是我到目前为止所做的:

$(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 个答案:

答案 0 :(得分:2)

如果我正确理解您的要求,它们如下:

  • 制作异步HTTP请求以获取一些HTML
  • 使用dataValModify()函数修改返回的HTML
  • 将修改后的HTML插入元素中,ID为:'ajaxTest'

如果是这样的话,那对我来说听起来就像你需要制作一个比现在使用的更低级别的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);
  }
});

答案 1 :(得分: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/