开发者

edit ajax data before adding it to html

开发者 https://www.devze.com 2023-03-27 06:27 出处:网络
Hi is it possible to edit the contents of a GET ajax request before appending it to the content of the page?

Hi is it possible to edit the contents of a GET ajax request before appending it to the content of the page?

I am getting the contents of the body of a new html page and would like to add some classes :).

This is probably impossible,

thank you 开发者_JS百科for your help!


It's definitely not impossible. You just need a way to parse it. The easiest way to do it would actually be to append it to your page in a hidden container and then do any DOM manipulations you need. Then you can just relocate the html or show it if it's in the right place.

If you are using jQuery, you can actually perform any of the jQuery operations on the html string that you get back. However, this is quite a bit less performant in certain older browsers.


The way to do this without jquery is using document.createDocumentFragment

ajax({ //Your preferred method
    done: function(response){
        var myDom = document.createDocumentFragment();
        myDom.innerHTML = response.responseText;
        // your manipulations same as you would with "document"
        document.appendChild(myDom);
    }
});

Resources:

  • MDN - createDocumentFragmant
  • W3C Spec


If you are using jQuery, you could try the following (note that it could be extremely resource-consuming, depending on your loaded page size):

$.ajax({
    /*parameters here*/
    success: function(data,textStatus){
        processData(data);
    }
});

function processData(data){
    //this line creates jQuery object that contains DOM model for loaded page
    var page = jQuery(data); 

    page.find('#id-of-element-to-add-some-class').addClass('*your class*');
    page.find('#table').addClass('myTable'); //adds class myTable to all tables in the document
    //placeholder for loaded page content. Could be something like $('#placeholder')
    var target_element = document; 

    $(target_element ).append(page);
}

See jQuery.ajax for details

0

精彩评论

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