使用jQuery在AJAX响应中通过ID查找元素 [英] Finding an element by ID in an AJAX Response with jQuery
问题描述
我需要将数据发布到php页面,然后我想获取响应中某个div的文本,但似乎无法正确设置.我对jQuery不太满意,但是我通常可以很快地解决问题……我已经花了一分钟的时间,尝试了我发现的所有内容……我想我只是缺少了正确的东西组合.
I need to post data to a php page and then I'd like to get the text of a certain div that is in the response but I can't seem to set things up correctly. I'm not too good with jQuery but I can usually figure things out fairly quickly... I've been at this for a minute and have tried everything I have found... I think I am just missing the right combination of stuff.
$.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);
的输出,红色框是我想要的响应...
this is the output of console.log(success);
and the red box is what I want from the response...
![这张照片看起来真的很小……当我拍出来的时候,它并不是那么小.我希望它仍然可读] [1]
![this picture seems really tiny... it wasn't that tiny when I made it. I hope it is still readable][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组成,则会遇到相同的问题.
And I have tried removing the style part and I added in the html, head and body tags in hope that it would help.... meaning, I have the same issues if the response only consists of the three divs.
推荐答案
请注意所有元素如何在同一级别上?您需要使用.filter()
将当前选择范围缩小到该选择范围内的单个元素,而.find()
将会查看当前选择范围的后代.
Notice how all of the elements are on the same level? You need to use .filter()
to narrow down the current selection to a single element in that selection, .find()
will instead look at the descendants of the current selection.
var success = $($.parseHTML(response)).filter("#success");
console.log(success); // div#success
这篇关于使用jQuery在AJAX响应中通过ID查找元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!