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

时间:2013-01-08 02:21:46

标签: javascript ajax jquery

我的问题如下:我已经开始在jQuery中使用$ .ajax函数,我想知道如何处理HTML页面的返回。请求完成,我可以在console.log中返回返回的HTML页面,但我现在想从该页面中选择一个元素。我有过几次尝试,其中包括:

$(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
 });

});

我知道我可以简单地使用.load(),你可以提供选择标准,但.ajax是开始的根函数,我想学习这种方式以及更复杂的查询。下半部分应该是我不应该尝试以这种方式选择元素而只是提供json或单个关键短语而不是整个html页面?感谢所有帮助。

2 个答案:

答案 0 :(得分:1)

只需将返回的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 );
    }
});

答案 1 :(得分:0)

如果你只想得到objects,约瑟夫上面的回答是正确的。

但如果你想加载那个元素的内容,你可以改变这个:
var paragraphs = $(html).find('p');

var paragraphs = $(html).find('p').html();

希望它有所帮助。

相关问题