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

前端 未结 10 1556
时光说笑
时光说笑 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:44

    Shamelessly copied and adapted from another of my answers (Simple jQuery ajax example not finding elements in returned HTML), this fetches the HTML of the remote page, then the parseHTML function creates a temporary div element for it and puts the lot inside, runs through it, and returns the requested element. jQuery then alerts the text() inside.

    $(document).ready(function(){
      $('input').click(function(){
        $.ajax({
          type : "POST",
          url : 'ajaxtestload.html',
          dataType : "html",
          success: function(data) {
            alert( data ); // shows whole dom
            var gotcha = parseHTML(data, 'TITLE'); // nodeName property returns uppercase
            if (gotcha) {
              alert($(gotcha).html()); // returns null
            }else{
              alert('Tag not found.');
            }
          },
          error : function() {
            alert("Sorry, The requested property could not be found.");
          }
        });
      });
    });
    
    function parseHTML(html, tagName) {
      var root = document.createElement("div");
      root.innerHTML = html;
      // Get all child nodes of root div
      var allChilds = root.childNodes;
      for (var i = 0; i < allChilds.length; i++) {
        if (allChilds[i].nodeName == tagName) {
          return allChilds[i];
        }
      }
      return false;
    }
    

    To get several items out or a list of script tags, say, I think you'd have to improve the parseHTML function, but hey - proof of concept :-)

提交回复
热议问题