我正在尝试获取任意输入的URL /页面的一些页面详细信息(页面标题,页面上的图像等).我有一个后端代理脚本,我通过ajax GET使用,以返回远程页面的完整HTML.一旦我得到ajax响应,我就试图在其上运行几个jQuery选择器来提取页面细节.这是一般的想法:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function (data) {
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", data);
//doesn't seem to work even if there is a title in the HTML string
var name = $(data).filter("title").first().text();
var description = $(data).filter("meta[name='description']").attr("content");
}
});
Run Code Online (Sandbox Code Playgroud)
有时使用$("selector", data)似乎工作,而其他时间$(data).filter("selector")似乎工作.有时候,都不行.当我只检查内容时$(data),似乎有些节点通过,但有些节点就消失了.有没有人知道在完整的HTML字符串上运行选择器的一致方法?
您的问题有点模糊,尤其是关于什么输入导致什么代码失败以及如何失败。它可能是格式错误的 HTML,导致事情变得混乱 - 但我只能猜测。
也就是说,你最好的选择是与以下人员合作$(data)而不是data:
$.ajax({
type: "GET",
url: base_url + "/Services/Proxy.aspx?url=" + url,
success: function(data) {
var $data = $(data);
//data is now the full html string contained at the url
//generally works for images
var potential_images = $("img", $data);
//doesn't seem to work even if there is a title in the HTML string
var name = $data.filter("title").first().text();
var description = $data.filter("meta[name='description']").attr("content");
}
});
Run Code Online (Sandbox Code Playgroud)