Simple jQuery ajax example not finding elements in returned HTML

后端 未结 4 1448
情话喂你
情话喂你 2020-12-25 08:27

I\'m trying to learn jQuery\'s ajax functions. I\'ve got it working, but jQuery doesn\'t find elements in the returned HTML DOM. In the same folder as jquery, run this page:

4条回答
  •  悲哀的现实
    2020-12-25 08:57

    I found that if ajaxtest-load.html does not have or tags but just a few html elements, it does work.

    Edit:

    If the input has to be a full HTML page, maybe you can first strip of the tags you don't want with string operations.. anyone?

    Edit 2:

    Vaguely remembered Javascript/DOM allowed for "temporary documents" which you could operate on and use the results from, then a bit of googling yielded a parseHTML function (http://www.daniweb.com/forums/post874892-2.html) which I've adapted to return the right bit:

    $(document).ready(function(){
      $('input').click(function(){
        $.ajax({
          type : "POST",
          url : 'ajaxtest-load.html',
          dataType : "html",
          success: function(data) {
            alert( data ); // shows whole dom
            var gotcha = parseHTML(data, 'wrapper');
            if (gotcha) {
              alert($(gotcha).html());
            }else{
              alert('ID not found.');
            }
          },
          error : function() {
            alert("Sorry, The requested property could not be found.");
          }
        });
      });
    });
    
    function parseHTML(html, idStr) {
      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].id && allChilds[i].id == idStr) {
          return allChilds[i];
        }
      }
      return false;
    }
    

    Does that work?

提交回复
热议问题