jquery ajax parse response text

前端 未结 5 1684
执念已碎
执念已碎 2020-12-03 12:19

Ok this is really frusturating me because I\'ve done this a hundred times before, and this time it isn\'t working. So I know I\'m doing something wrong, I just can\'t figur

相关标签:
5条回答
  • 2020-12-03 12:30

    You cannot pull in an entire XHTML document. You can only handle tags that exist within the <body> of an html document. Frustrating. Strip everything from info.html that isn't within your <body> tag and try it again.

    There are other potential ways around this issue - check below "Stackoverflow Related Items" at the base of this response.

    From the Doc: (http://docs.jquery.com/Core/jQuery#htmlownerDocument)

    "HTML string cannot contain elements that are invalid within a div, such as html, head, body, or title elements."

    Stackoverflow Related Items:

    • Simple jQuery ajax example not finding elements in returned HTML
    • What is the best practice for parsing remote content with jQuery?
    0 讨论(0)
  • 2020-12-03 12:32

    I know this is an old post but I've been having the EXACT same frustrating problem for a couple of hours and have found a solution. For me what actually worked was to have the html content wrapped with a form tag.

    So having the following html source:

    <html>
     <head>
      <body>
       <form>
        <div id="content">Some Stuff</div>
       </form>
      </body>
     </head>
    </html>
    

    With this jquery snippet should work:

    var callback = function (data) {
       alert($("#content", $(data)).html());
    };
    $.get(url, null, callback, null);
    

    Hope this helps...

    0 讨论(0)
  • 2020-12-03 12:45

    Wanting to do the same thing and knowing that JQuery load(..) does it, I had a look in the code. While you can't turn a complete html response directly into a JQuery object, you can append it to one so:

    function(data, textStatus, xhr) {
        $(target).html(jQuery("<div>").append(data).find("#snippet"));
        // Create a dummy div to hold the results,
        // inject the contents of the document into it,
        // Locate the specified elements
    }
    

    The response from the server that goes into data is like:

    <! doctype ... >
    <html>
      <head>
        ...
      </head>
      <body>
        <div id="snippet">
          <p>Some content here that we are interested in</p>
        </div>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-12-03 12:47

    Try including whole body within a <div> tag, e.g. <body><div>content</div></body>.

    0 讨论(0)
  • 2020-12-03 12:50

    I have found this being pretty clean solution:

    var elementInResponse = $("<div>").html(responseText).find(selector);
    
    0 讨论(0)
提交回复
热议问题