parse title of other urls using jquery
i am looking for a way to get title of urls mentioned in the webpage. I tried 开发者_JAVA百科http://urldecoderonline.com/ but it does not provide a way to parse the page.
Just for ex: user enters a url say http://www.google.com in a text input box and on pressing a submit button i would like to alert him with a title of "http://www.google.com"
Any ideas??
you need to use ajax and a php ajax proxy script on your server
i didn't test this, but it should work
ajax_proxy.php
<?php
if(isset($_POST["url"]){
echo file_get_contents($_POST["url"]);
}
?>
js
$(document).ready(function(){
$("#submit").click(function(){
$.ajax({
type: "post",
dataType: "text",
url: "ajax_proxy.php",
data: { url: $("#input").val() }
success: function(data){
alert($(data).find("title").html());
}
});
});
});
If the problem is to extract the host part from the URL string, then this is a typical regular expression problem.
If there's something before the first semicolon, that's the protocol. Everything from there up to the forward slash is the host.
Something along the line of:
<http>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function parseUrl(url) {
var regexStringProtocol = '^([A-Za-z]*)://';
var protocolResults=new RegExp(regexStringProtocol).exec(url);
if(protocolResults) {
var protocol = protocolResults[1];
url = url.substring(protocolResults[0].length);
}
else {
var protocol = '';
}
var regexStringHost = '^([^/^?]+)';
var hostResults = new RegExp(regexStringHost).exec(url);
if(hostResults) {
var host = hostResults[1];
}
else {
host = '';
}
alert('Protocol: ' + protocol + '\nHost: ' + host);
// Continue parsing if you care about the part and the parameters
}
$(function() {
$('input').val('http://stackoverflow.com/questions/6715438/parse-title-of-other-urls-using-jquery/6715527#6715527');
$('#parse').click(function() { parseUrl($('input').val());});
}
);
</script>
</head>
<body>
<input type="text" style='width:150mm' />
<br />
<button id="parse">Parse</button>
</body>
</html>
To get title of a href link you can use attr
function of jQuery.
$("a").attr("title");
To get titles of all links on page:
$("a").each(function(){
var title = $(this).attr("title");
});
精彩评论