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

我需要将数据发布到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);的输出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 

回应是……

   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; }    
Total new rows added: 0 out of 0


Total updated rows: 0 out of 0
true

我已经尝试删除样式部分,我添加了html,head和body标签,希望它会有所帮助……意思是,如果响应只包含三个div,我会遇到同样的问题。

注意所有元素是如何在同一级别上的 ? 您需要使用.filter()将当前选择范围缩小到该选择中的单个元素,而.find()将查看当前选择的后代。

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

我有一个由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 '...' $('#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()也适用于当前元素是您正在寻找的。 好吧,可能这个post与@Kevin的答案非常相似,只是建议另一个替代答案并提供更多细节,希望能让事情更清楚。