【发布时间】:2017-03-28 00:14:25
【问题描述】:
我正在对服务器进行 GET 调用,它返回一个 HTML 字符串。我想解析这个 HTML,只获取 ID 为“容器”的 HTML。
这是我的代码:
$("#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;
});
我只想输出 ID 为“容器”的 HTML。现在它什么也没输出。我不认为我这样做是最好的方式。
另外:我将把 HTML 加载到页面上的另一个元素中。
【问题讨论】:
-
你可以把它放到一个不可见的元素中并使用DOM。
-
或成为真正的程序员并使用
DOMParser -
你会用它做什么?如果您只是要将其加载到页面上的另一个元素中,请使用带有页面片段 ID 的
load。 -
@MikeMcCaughan 是的,我将加载到另一个元素中。刚刚点击了你的链接。看起来它会起作用!
-
直接转到我上一条评论中的链接即可;它解释了如何从另一个 URL 加载到另一个元素中,并指定要从中提取的元素的 ID。
标签: javascript jquery html ajax rest