简体   繁体   English

jQuery AJAX:如何查询返回的HTML文档

[英]jQuery AJAX : How to query an returned HTML document

My question is as follows: I have started using the $.ajax function with jQuery and I am wondering how I work with the return of an HTML page. 我的问题如下:我已经开始在jQuery中使用$ .ajax函数,并且想知道如何处理HTML页面的返回。 The request completes and I can console.log the returned HTML page however I would now like to select a single element from that page. 请求完成,我可以console.log返回的HTML页面,但是我现在想从该页面中选择一个元素。 I have had several attempts which included: 我进行了几次尝试,包括:

$(data).find('p');

$('button').click(function() {

  $.ajax(funciton() {
  dataType: 'html',.
  url: 'localhost/sw',
  success: function(data) {
      // This is where I would like to select a element or node from the complete
      // returned html document
 });

});

I know i can simply use .load() which you can provide select criteria but .ajax is the root function to begin with and I would like to learn that way as well for more complicated queries. 我知道我可以简单地使用.load()来提供选择条件,但是.ajax是开始的根函数,对于更复杂的查询,我也想学习这种方式。 Second half of this would be should I not be trying to select elements this way and just serve up json or a single key phrase instead of the entire html page? 下半部分应该是我不应该尝试以这种方式选择元素,而只提供json或单个关键字而不是整个html页面吗? All help is appreciated. 感谢所有帮助。

Just pass the returned HTML to jQuery, and treat it like a regular jQuery collection: 只需将返回的HTML传递给jQuery,并将其视为常规jQuery集合即可:

$.ajax({
    dataType: 'html',.
    url: 'localhost/sw',
    success: function (html) {
        var paragraphs = $(html).find('p');
        // Manipulate `paragraphs` however you like. For example:
        $(document.body).append( paragraphs );
    }
});

Joseph's answer above is correct if you just want to get the objects . 如果您只想获取objects上述约瑟夫的答案是正确的。

But if you want to load the content of that element, you may change this: 但是,如果要加载该元素的内容,则可以更改以下内容:
var paragraphs = $(html).find('p');
to
var paragraphs = $(html).find('p').html();

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM