use*_*390 16 javascript jquery get title
我是新手,如果这是一个愚蠢的问题,请原谅.
所以我尝试的是使用JQuery/JS获取URL的标题.我不想加载网址的内容,然后在其中解析标签.
让我更清楚一点,我有一组网址,比方说20我要显示标题..我所指的网址不是当前的网址,所以我不能使用js document.title ..
所以我想做一些SOMEFUNC.title(URL)的形式并得到它的标题.有这样的功能吗?
unc*_*ive 17
这样的事情应该有效:
$.ajax({
url: externalUrl,
async: true,
success: function(data) {
var matches = data.match(/<title>(.*?)<\/title>/);
alert(matches[0]);
}
});
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
然后在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);
}
});
}
Run Code Online (Sandbox Code Playgroud)
小智 11
您还可以使用此API获取任何网页的标题
http://textance.herokuapp.com/title/
$.ajax({
url: "http://textance.herokuapp.com/title/www.bbc.co.uk",
complete: function(data) {
alert(data.responseText);
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
35210 次 |
| 最近记录: |