简体   繁体   English

从HTML获取标题

[英]Get title from HTML

I have a server side function which returns content of HTML page: 我有一个服务器端函数,该函数返回HTML页面的内容:

if (Meteor.isServer) {
  Meteor.startup(function () {
    // code to run on server at startup

    Meteor.methods({
      sayHello: function() {
        var response = Meteor.http.call("GET", "http://google.com");
        return response;
      }
    });
  });

And I have client code where I am trying to get title from this HTML page: 我在尝试从此HTML页面获取标题的客户端代码:

'click .add_tag' : function(e,t) { //Session.set('editing_tag_id', e.target.id); 'click .add_tag':function(e,t){//Session.set('editing_tag_id',e.target.id);

  Meteor.call("sayHello", function(err, response) {
    var title = $(response.content).find("title").text();
    var title2 = $(response).find("title").text();
    var title3 = response.content.match(/<title[^>]*>([^<]+)<\/title>/)[1];
    alert(title3);
  });

I would like to get jQuery version ('title' or 'title2'), but it doesn't works. 我想获取jQuery版本(“ title”或“ title2”),但是它不起作用。 It returns empty string. 它返回空字符串。

'Title3' - version works fine, but I don't like regexps. 'Title3'-版本工作正常,但我不喜欢正则表达式。 :) :)

Is there any way to make 'jQuery'-versions works ? 有什么办法可以使“ jQuery”版本起作用?

As requested, I will reiterate my comment as an answer... 根据要求,我将重申我的评论作为答案...

I would stick with the regex, even though you don't like it. 即使您不喜欢它,我也会坚持使用正则表达式。 There is a huge overhead of constructing a DOM element that is essentially an entire page, purely for the purpose of parsing a small amount of text. 纯粹出于解析少量文本的目的,构造本质上是整个页面的DOM元素会产生巨大的开销。 The regex is more lightweight and will perform adequately in slower browsers or on slower machines. regex更轻巧,可以在速度较慢的浏览器或速度较慢的计算机上正常运行。

Wrap response.content in a <div> and then do a selection off of that. response.content包裹在<div> ,然后进行选择。 This way you have a proper structure to start from rather than an array that you might actually be getting. 这样,您就可以从一个适当的结构开始,而不是从一个实际可能得到的数组开始。

var $wrap = $("<div></div>").html(response.content);
$wrap.find("title").text();

An example of what is probably going on: http://jsfiddle.net/UFtJV/ 一个可能发生的情况的示例: http : //jsfiddle.net/UFtJV/

Don't forget one thing : you should never return HTML to client. 不要忘记一件事:永远不要将HTML返回给客户端。 You should return Json (or even Xml) that your client will transform into Html using Template. 您应该返回Json(甚至Xml),您的客户端将使用Template转换为Html。 You are doing like a lot of dev doing Bad Ajax. 您的工作就像许多开发Bad Ajax的开发人员一样。

Don't forget : "only data on wire, not display". 不要忘记:“仅在线数据,不显示”。

So there should not be any problem coz, on response you just have to take data from Json formatted response and inject it inside your Template. 因此,应该没有任何问题,响应时,您只需从Json格式的响应中获取数据并将其注入到Template中即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM