【问题标题】:Javascript / jQuery $.get(url) Title Parsing not WorkingJavascript / jQuery $.get(url) 标题解析不起作用
【发布时间】:2010-05-26 18:49:13
【问题描述】:

即使以下方法有效: http://jsfiddle.net/N7D5r/

我尝试使用相同的代码没有正确获得标题。无论出于什么奇怪的原因,它们都会返回 null:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    // Act on each link
    $('a').each(function(eachIteration){

        // Store current link's url
        var url = $(this).attr("href");

        $.get(url, function(response){
            alert("This is the url: " + url);
            if (((/<title>(.*?)<\/title>/m).exec(response)) != null)
                alert("This would be the title: " + (/<title>(.*?)<\/title>/m).exec(response)[1]);
            else
                alert("title was null");
         });        

    });
});
</script>
<title>test</title>
</head>

<body>
<p><a href="javascript:;">Javascript link</a></p>
<p>&nbsp;<a href="http://www.latentmotion.com">Misc. Link</a> and what else... <a href="http://www.latentmotion.com/how-to-create-a-jquery-bookmarklet/#comment-52004762">jQuery Bookmarklet Link</a></p>
<p> Some <a href="#test">anchor link</a> test.</p>
</body>
</html>

有什么想法吗?


注意: 这个问题是对位于此处的堆栈溢出问题的跟进: jQuery Can't $(...).load() the head title in Chrome

【问题讨论】:

  • 怎么不行?整个“响应”是什么样的?代码是说标题为空,还是给出了错误的结果?
  • 这段代码对我有用,只是粘贴到一个新的 HTML 页面中。您是否尝试在本地运行它?如果是这样,您可能需要允许它访问外部内容。
  • 它不起作用,我的意思是它没有从链接中获取标题。即使网址确实有标题,它也会运行“标题为空”。
  • 这在 IE8 中对我有用,但在 Chrome 中不起作用,所以不确定您是否有兼容性问题。

标签: javascript jquery ajax get title


【解决方案1】:

This is the url: /users/recent/205784 This would be the title: User antimatter15 - Recent - Stack Overflow This is the url: /about This would be the title: About - Stack Overflow This is the url: /faq This would be the title: FAQ - Stack Overflow This is the url: /users/205784/antimatter15

您的代码似乎有效。会不会是链接不在当前域内,违反了同源策略?

【讨论】:

猜你喜欢
  • 2014-02-02
  • 2013-11-07
  • 2011-12-12
  • 1970-01-01
  • 2015-10-16
  • 1970-01-01
  • 2017-04-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多