使用jQuery在AJAX响应中通过ID查找元素

24
我需要向php页面发布数据,然后我想获取响应中某个div的文本,但我似乎无法正确地设置它们。我对jQuery不是太熟悉,但通常可以很快弄清楚...我已经尝试了一切,但我认为我只是缺少正确的组合。
$.post("process.php", data , function (response) {  

       var w = window.open();    

       $(w.document.body).html(response); 

       console.log(typeof response); //  yeilds string 
       //create jquery object from the response html
       // var $data = $(response);   // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text


       var success =  $($.parseHTML(response)).find("#success"); 
       console.log('success'); 
       console.log(success);        // see screenshot
       console.log(success.text()); // yields nothing 
       console.log(success.val());  // yields undefined 
       // if (window.focus) {w.focus()}; 

 },'html');  

这是console.log(success);的输出结果,而红框内的内容则是我想要从响应中获取的...

![这张图片看起来很小...我制作时它并不小。我希望它仍然可读性很强][1]

而这个则会实现那个效果:

var success =  $(response).find("#success"); 
console.log('success'); 
console.log(success);        // yeilds Uncaught Error: Syntax error, unrecognized expression: + whole html text in red

响应是...

<html><head>
   <style>

      div.totals {
          font-family:calibri; font-size:.9em;  display:inline-block; 
          border-width: 2px;  border-style: solid; border-color: #FFD324; 
          background-color: #FAF5D7; color: #514721; 
          width: 500px; 
          }

      div.error_invalid {
         font-family:calibri; font-size:.9em;  display:inline-block; 
         border-width: 2px; border-style: solid; border-color: #9999CC; 
         background-color: #EEEEFF; color: #7979B8; 
     }

    </style>
    </head>
    <body>
    <div class="totals">Total new rows added: 0 out of 0<br/></div>
    <br/><br/>
    <div class="totals">Total updated rows: 0 out of 0 <br/></div>

    <div id="success">true</div>
    </body></html> 

我已经尝试过删除样式部分并在 HTML 中添加 head、body 标签,希望它会有所帮助...也就是说,如果响应只包含三个 div,我仍然面临相同的问题。


可以展示respone的内容。 - pktangyue
是的。我不确定是否需要,因为屏幕截图中给我的内容在那个时候似乎被正确解释了。 - gloomy.penguin
你是否尝试过 $(w.document.body).find('#success') - pktangyue
3个回答

44

注意所有元素都在同一 级别 上吗? 您需要使用 .filter() 将当前选择缩小为该选择中的单个元素,而 .find() 则会查看当前选择的后代。

var success =  $($.parseHTML(response)).filter("#success"); 
console.log(success); // div#success

1
谢谢。你能告诉我为什么有时候在谷歌搜索这个问题时,他们说要使用 $(response),而其他时候则是 $($.parseHTML(response)) 吗? - gloomy.penguin
3
$.parseHTML是在1.8版本中新增的方法,专门用于解析HTML。使用$.parseHTML更加安全,它可以解决IE10某些边缘情况下的内存泄漏问题,但我不确定它还有什么其他作用。 - Kevin B
1
jQuery 1.9改变了ajax中处理HTML的方式。具体来说,不允许有前导空白字符。请参阅https://github.com/jquery/jquery-migrate/blob/master/warnings.md获取详细信息。 - Donald T
5
在我的情况下,“filter”没有起作用,只有“find”起作用。我正在使用jQuery 1.9.1。 - machineaddict
console.log(success.html()) - Kevin B
显示剩余2条评论

4
我通过 AJAX 获取了一个完整的 'html' 页面,但我只需要其中一部分内容,这部分内容被包裹在一个 div 中,而且我还需要执行 'html' 页面中的脚本。
 $.ajax ({
  type: "POST",
  url : "contact.php",
  data: $("#formContactUs").serialize(),
  success: function(msg){
    console.log($(msg)); // this would returned as an array
    console.log(msg);    // return whole html page as string '<html><body>...</body></html>'
    $('#id').html($(content).closest('.target-class'));
    $('#id').append($(content).closest('script')[0]);  // append and execute first script found, when there is more than one script.
  }
});

@kevin的回答给出了find()方法不能如预期工作的提示,因为它只选择其后代而不是在考虑的第一个元素下选择。除了使用filter方法,如果当前元素就是您要查找的元素,则$.closest()也可以起作用。嗯,可能这篇文章与@Kevin的答案非常相似,只是提供另一种替代答案并提供更多细节,希望能使事情更清晰明了。


2
如果上述答案无法解决问题,请尝试以下方法。
var successHtml = $($.parseHTML(response)).find("#success").html();

1
谢谢兄弟,真的,愿上帝保佑你,我找了两天才找到,哈哈 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接