我正在尝试像这里一样加载页面的主体:jQuery: Load body of page into variable .
但是,在此线程中没有人提供有效的解决方案,因为 $.load()
切断 <!DOCTYPE>
, <html>
和 <body>
默认标记(afaik)。我选择了 $.get()
方法,我已经将页面的全部内容作为字符串获取,但现在我无法只获取 <body>
标签(或更确切地说:<body>
标签内的内容)。
到目前为止我已经尝试过:
$.get(uri, function(data){
console.log(data); // --> the entire page's content is logged
});
$.get(uri, function(data){
console.log($(data)); // --> i guess that's the entire site as an object
});
$.get(uri, function(data){
console.log($(data).find("body")); // --> this should be the <body> tag as an object, but console just outputs "[ ]"
});
最佳答案
说明
嗯..让我们看看我是否可以正确地证明这一点。
所以当你这样做的时候
$.get(uri, function(data){
console.log(data); // --> the entire page's content is logged
});
你真的在做这个
$.ajax({
url: uri,
type: "GET",
success: function(msg){
console.log(msg);
}
});
默认情况下,它以 HTML 格式返回页面。或者更确切地说,默认情况下,它首先检查页面上的 MIME 类型,如果未找到,则返回 HTML。如果你想告诉它你想返回什么,你可以在服务器页面上以 MIME 类型进行,或者你可以使用 $.getJSON()
如果您希望以对象的形式从请求中返回数据,JSON 是最佳选择。 实际上,代码中唯一真正的区别是
替换你的
$.get()
与$.getJSON()
$.getJSON(uri, function(data){ console.log(JSON.stringify(data)); });
或
添加
dataType: "json"
在$.ajax()
$.ajax({ url: uri, type: "GET", dataType: "json", success: function(data){ console.log(JSON.stringify(data)); } });
因此它可以期望从页面返回 JSON 数据。
现在您需要做的就是在服务器端准备数据,使用 json_encode()
$output = array(
"msg" => "This is output",
"data" => array(
"info" => "Spaaaace",
"cake" => "no"
),
array(
"foo",
"bar"
)
);
echo json_encode($output);
//it will look like this before the text is parsed into JSON in Javascript
//{"msg":"This is output","data":{"info":"Spaaaace","cake":"no"},"0":["foo","bar"]}
如果您希望从请求中返回对象,这是可行的方法。
解决方案
除了服务器端修复 json_encode()
,这就是解决方案。
$.getJSON(uri, function(data){
console.log(JSON.stringify(data));
});
替代方案
假设您想保留您的 $.get()
您只需要 <body>
之间的文本和 </body>
Here's an example
$.get(uri, function(msg){
var startWith = "<body>",
endWith = "</body>";
var iStart = msg.search(startWith);
var iEnd = msg.search(endWith);
msg= msg.substring(iStart+startWith.length, iEnd)
console.log(msg);
});
和here's关于那个的更高级的答案。
关于页面的 jQuery 加载主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8680719/