Simple jQuery ajax example not finding elements in returned HTML

后端 未结 4 1423
情话喂你
情话喂你 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:51

    This is not a direct answer, but may help to clarify things.

    The data parameter of the callback function can be made into a jQuery (1.6.2) object $(data), which contains the different parts of the HTML response:

    • Stuff that precedes the actual document, such as a doctype declaration, or ignorable white space textnodes.
    • The contents of the head element.
    • The contents of the body element.

    The html, head and body elements are not in the data object. Since the number of elements contained in head and body may vary, you should not get them by indexing like $(data)[2]. Instead, apply a filter to this object, like this:

            $.get(
              uri,
              function(data, textStatus, jqXHR){
                var $doc = $(data);
                var title = $doc.filter('title').text();
                // title is the title from the head element.
                // Do whatever you need to do here.
              }
            );
    

    After filtering the right elements, you can apply further selectors using find().

    Unfortunately, in IE the head elements are not part of $(data). I have no idea why this is.

提交回复
热议问题