开发者

How can I manipulate an Ajax response before it's injected into the DOM?

Here is what I have so far:

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

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

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

How can I take the Ajax response and modify it before it is injected into the DOM? Previously, I was binding ajaxComplete and modifying the DOM directly after injection, but I would like to modify the response instead. I don't think it makes a lot of sense to find elements in the Ajax response and use them to modify the DOM. I send the xhr.responseText into my function so that I don't reapply the modifications to the rest of the body, which will have already been modified by the time of an Ajax call. Also, is there something better than xhr.responseText to use for this? I couldn't get xhr.responseHTML to work.

EDIT: Right now I'm ju开发者_运维百科st using a simple test Ajax call to return an MVC partial view:

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


If I'm understanding your requirements correctly, they are as follows:

  • Make an asynchronous HTTP request to get some HTML
  • Modify the returned HTML using the dataValModify() function
  • Insert the modified HTML into your element with the ID: 'ajaxTest'

If so then it sounds to me like you need to make a lower level ajax call than what you're using at present i.e. $(elem).load()

Essentially the call to .load() is a wrapper for $.get() followed by a call to $(elem).html(someContent) where "someContent" is the responseText from the HTTP request.

Therefore if you want to modify the response before it's injected into the DOM, then you can do something similar to the following:

$.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);
  }
});


You can use ajaxComplete to modify the responseHTML itself.

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

Update: I haven't tried it, but it might help:

$.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;
      }
    }
  }
});

More info here: http://api.jquery.com/extending-ajax/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜