What is the best practice for parsing remote content with jQuery?

前端 未结 10 1471
时光说笑
时光说笑 2020-11-27 03:21

Following a jQuery ajax call to retrieve an entire XHTML document, what is the best way to select specific elements from the resulting string? Perhaps there is a library or

相关标签:
10条回答
  • 2020-11-27 03:53

    Instead of hacking jQuery to do this I'd suggest you drop out of jQuery for a minute and use raw XML dom methods. Using XML Dom methods you would can do this:

      window.onload = function(){ 
        $.ajax({
              type: 'GET', 
              url: 'text.html',
              dataType: 'html',
              success: function(data) {
    
                //cross platform xml object creation from w3schools
                try //Internet Explorer
                  {
                  xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
                  xmlDoc.async="false";
                  xmlDoc.loadXML(data);
                  }
                catch(e)
                  {
                  try // Firefox, Mozilla, Opera, etc.
                    {
                    parser=new DOMParser();
                    xmlDoc=parser.parseFromString(data,"text/xml");
                    }
                  catch(e)
                    {
                    alert(e.message);
                    return;
                    }
                  }
    
                alert(xmlDoc.getElementsByTagName("title")[0].childNodes[0].nodeValue);
              }
        });
      }
    

    No messing about with iframes etc.

    0 讨论(0)
  • 2020-11-27 03:55

    How about some quick tag renaming?

    $.ajax({
        type : "GET",
        url : 'results.html',
        dataType : "html",
        success: function(data) {
    
            data = data.replace(/html/g, "xhtmlx");
            data = data.replace(/head/g, "xheadx");
            data = data.replace(/title/g, "xtitlex");
            data = data.replace(/body/g, "xbodyx");
    
            alert($(data).find("xtitlex").text());
        }
    
    });
    
    0 讨论(0)
  • 2020-11-27 03:55

    After parsing the XML string into an XML DOM, I'd either use jQuery on it directly (you can do this by providing a context to the jQUery selector, such as $(':title', xdoc.rootElement) or using XPath (works in Firefox; there are supposedly libraries for IE but I haven't had good success with them).

    0 讨论(0)
  • 2020-11-27 04:01

    Inspired from this answer, but with deferred:

    function fetchDoc(url) {
      var dfd;
      dfd = $.Deferred();
    
      $.get(url).done(function (data, textStatus, jqXHR) {
    
        var $iframe = $('<iframe style="display:none;"/>').appendTo('body');
        var $doc = $iframe.contents();
        var doc = $doc[0];
    
        $iframe.load(function() {
          dfd.resolveWith(doc, [data, textStatus, jqXHR]);
          return $iframe.remove();
        });
        doc.open();
        doc.write(data);
    
        return doc.close();
      }).fail(dfd.reject);
    
      return dfd.promise();
    };
    

    And smoke it with:

    fetchDoc('/foo.html').done(function (data, textStatus, jqXHR) {
      alert($('title', this).text());
    });
    

    LIVE DEMO (click 'Run')

    0 讨论(0)
提交回复
热议问题