我是个新手,如果这是个愚蠢的问题,请原谅..
因此,我尝试使用JQuery/JS获取URL的标题。我不想加载url的内容,然后解析其中的标签。
让我更清楚地说,我有一组urls,比如20个,我想要显示其标题。我所指的document.title不是当前的urls,所以我不能使用js urls ..
因此,我想做一些形式SOMEFUNC.title(网址),并获得它的标题。有这样的功能吗?
发布于 2012-07-01 22:39:02
您还可以使用此API获取任何网页的标题
http://textance.herokuapp.com/title/
$.ajax({
url: "http://textance.herokuapp.com/title/www.bbc.co.uk",
complete: function(data) {
alert(data.responseText);
}
});
发布于 2011-10-26 19:15:43
像这样的东西应该是有效的:
$.ajax({
url: externalUrl,
async: true,
success: function(data) {
var matches = data.match(/<title>(.*?)<\/title>/);
alert(matches[0]);
}
});
TheSuperTramp是正确的,如果externalUrl在您的域外,上面的内容将不起作用。取而代之的是创建php文件get_external_content.php:
<?php
function file_get_contents_curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$url = $_REQUEST["url"];
$html = file_get_contents_curl($url);
preg_match('/<title>(.+)<\/title>/',$html,$matches);
$title = $matches[1];
echo json_encode(array("url" => $url, "title" => $title));
然后在javascript中:
function getTitle(externalUrl){
var proxyurl = "http://localhost/get_external_content.php?url=" + externalUrl;
$.ajax({
url: proxyurl,
async: true,
success: function(response) {
alert(response);
},
error: function(e) {
alert("error! " + e);
}
});
}
发布于 2011-10-26 20:26:08
跨域请求不适用于ajax,但您可以在服务器上编写一个脚本来获取给定站点的标题。
如果您使用的是PHP,您可以使用file_get_contents和preg_match函数来获取标题。这里的这个人已经提供了代码。
http://www.cafewebmaster.com/php-get-page-title-function
然后,在jQuery中,您可以将其添加到事件中,或者将其放入函数中。
//For the purpose of this example let's use google
var url = "http://www.google.com";
$.ajax({
type: "POST",
url: "./getURLTitle.php",
data: "{url: \"" + url + "\"}",
success: function(data) {
//do stuff here with the result
alert(data);
}
});
https://stackoverflow.com/questions/7901760
复制相似问题