我需要将数据发布到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标签,希望对您有所帮助。
请注意,所有元素如何都处于同一级别?您需要使用.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 '<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()不能按预期工作,因为它仅选择其后代,而不考虑所考虑的第一个元素。除了使用过滤器,如果当前元素是您要查找的,$。closest()也可以使用。好吧,可能这篇帖子与@Kevin的答案非常相似,只是为了建议另一个替代答案,并提供了更多细节,希望可以使事情变得更清楚。
如果上述答案不起作用,请尝试以下方法
var successHtml = $($.parseHTML(response)).find("#success").html();
本文地址:http://jquery.askforanswer.com/shiyongjqueryzaiajaxxiangyingzhongtongguoidchazhaoyuansu.html
文章标签:ajax , jquery , selector
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
文章标签:ajax , jquery , selector
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!