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

前端 未结 10 1629
时光说笑
时光说笑 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.

提交回复
热议问题