[英]How can I parse HTML returned from AJAX call
I am making a GET call to the server and it returns a String of HTML. 我正在对服务器进行GET调用,它返回HTML字符串。 I want to parse this HTML and only get the HTML with the id 'container'.
我想解析此HTML,仅获取ID为“容器”的HTML。
Here is my code: 这是我的代码:
$("#name").click(function() {
$.ajax({
type : 'GET',
url : "/",
dataType : 'text',
success : function(data) {
var object = $('<div/>').html(data).contents(); //Convert the String into an object.
var container = object.find('container'); //This successfully gets the object with the id 'container'
console.info(container.html()); //Here is where I want to output just the HTML of the container.
},
error : function(data) {
console.error("Error getting homepage");
}
});
return false;
});
I want to just output the HTML that has the id 'container'. 我只想输出具有ID“容器”的HTML。 Right now it is outputting nothing.
现在它什么也没输出。 I don't think I am doing this in the best way.
我认为我并没有做到最好。
ALSO: I am going to be loading the HTML into another element on the page. 另外:我将把HTML加载到页面上的另一个元素中。
This is what I used in my own code: 这是我在自己的代码中使用的:
var xhr = new XMLHttpRequest();
var url = "http://....";
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
html = $.parseHTML( xhr.responseText );
var container = $("#container", html);
}
}
I was able to accomplish what I wanted with the following: 我可以通过以下方式完成我想要的:
$("#name").click(function() {
$.ajax({
type : 'GET',
url : "/",
dataType : 'text',
success : function(data) {
var parser = new DOMParser();
doc = parser.parseFromString(data, "text/html");
var remainder = doc.getElementById("main-content").innerHTML;
$("#r-div").replaceWith("<div id=\"main-content\">" + remainder + "</div>");
},
error : function(data) {
console.error("Error getting homepage");
}
});
return false;
}); });
This gets a HTML response then extracts "main-content" div and replaces "r-div" in the current page with the HTML 这将获得HTML响应,然后提取“主要内容” div并将当前页面中的“ r-div”替换为HTML
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.