简体   繁体   中英

ajax make responseText to be an object

I need to get ajax answer as DOM object.

This is my code:

$.ajax(URL, {
    async: false,
    complete: function(e){
        code = $(e.responseText);
        alert( code.find('body').length );
    }
});

So I need to make response as an object and then make selection in it.

But in previous sample my Firebug returns:

Object[<TextNode textContent="\n\n \n ">, title, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">, meta, <TextNode textContent="\n">

For example, this code works fine:

$.get(URL, function(e){
    var code = $(e);
    alert( code.find('body').length );
});

But I need to make async request, so $.get is not an option (or I can't find solution with it).

Thanks for advise!

Your ajax code is not correct that should be something like this and you can get the response in the success callback instead:

$.ajax({
   url:URL,
   type : "get", 
   dataType: "html", // expected output from the requested url
   success: function(e){
      code = $(e.responseText); // or try with $(e) only
      alert( code.find('body').length );
   }, 
   error: function(err){
      alert(err.responseText);
   }
});

The only solution that I found at this moment is to make returned data as html and then it will able to manipulate with it. My working example is:

$.ajax({
    url: URL,
    async: false,
    type : "get",
    dataType: "html",
    success: function(data){
        var response = $('<html/>').html(data);
        alert(response.find('#ELEM').length);
    }
});

So, as you can see - I made response data to be HTML and it helps me to use .find() and other helpful things.

Hope this solution will be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM