javascript 从 ajax jquery post 响应中获取 <h2> 元素内的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19558700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the text inside <h2> element from an ajax jquery post response
提问by ABHILASH SB
Is there any way to get the text inside an element which is a response from an ajax jquery load. I need to get the text inside element which is present inside the response text from ajax page. Following is my ajax code:
有什么方法可以获取元素中的文本,该元素是来自 ajax jquery 负载的响应。我需要从ajax页面获取响应文本中存在的元素内的文本。以下是我的ajax代码:
var url = '...';
var saveData = $.ajax({
type: 'POST',
url: url,
data: {data : data},
dataType: "text",
success: function (resultData) {
callback(resultData); // need to get the <h2> text here..
}
});
saveData.error(function () {
console.log("Request to API not send");
});
回答by MrCode
You can pass HTML to jQuery and use it in the same way as if the element was on the DOM, for example with find()
:
您可以将 HTML 传递给 jQuery 并以与元素在 DOM 上相同的方式使用它,例如find()
:
console.log( $(resultData).find('h2').text() );
If your HTML doesn't have a root element then you can wrap it like so:
如果您的 HTML 没有根元素,那么您可以像这样包装它:
resultData = '<div>' + resultData + '</div>';
console.log( $(resultData).find('h2').text() );
回答by ST3
How about:
怎么样:
$(resultData).find('h2').text()
$(resultData).find('h2').text()