我是新手,如果这是一个愚蠢的问题,请原谅我..
所以我想要的是使用 JQuery/JS 获取 URL 的标题。我不想加载 url 的内容,然后解析其中的标签。
让我更清楚一点,我有一组网址,比如 20 个,我想显示标题..我所指的网址不是当前的网址,所以我不能使用 js document.title ..
所以我想做一些类似 SOMEFUNC.title(URL) 的事情并得到它的标题。有没有这样的功能?
我是新手,如果这是一个愚蠢的问题,请原谅我..
所以我想要的是使用 JQuery/JS 获取 URL 的标题。我不想加载 url 的内容,然后解析其中的标签。
让我更清楚一点,我有一组网址,比如 20 个,我想显示标题..我所指的网址不是当前的网址,所以我不能使用 js document.title ..
所以我想做一些类似 SOMEFUNC.title(URL) 的事情并得到它的标题。有没有这样的功能?
这样的事情应该工作:
$.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);
}
});
}
您还可以使用此 API 获取任何网页的标题
http://textance.herokuapp.com/title/
$.ajax({
url: "http://textance.herokuapp.com/title/www.bbc.co.uk",
complete: function(data) {
alert(data.responseText);
}
});
跨域请求不适用于 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);
}
});