代码之家  ›  专栏  ›  技术社区  ›  Xiong Chiamiov

javascript bookmarklet在“()”上给出语法错误

  •  1
  • Xiong Chiamiov  · 技术社区  · 14 年前

    我试图制作一个书签,它将加载我的网页上的黑客新闻讨论,如果它存在的话。

    这是代码,因为我要在node.js的REPL中运行它:

    // node.js stuff
    require.paths.unshift('.');
    var sys = require('util');
    var alert = sys.puts;
    var XMLHttpRequest = require("XMLHttpRequest").XMLHttpRequest;
    
    //javascript: (function () {
        //url = 'http://api.ihackernews.com/getid?url=' + encodeURIComponent(window.location.href);
        url = 'http://api.ihackernews.com/getid?url=' + encodeURIComponent('http://blog.asmartbear.com/self-doubt-fraud.html');
        http = new XMLHttpRequest();
        http.open("GET", url, true);
    
        http.onreadystatechange = (function () {
            if (this.readyState == 4) {
                alert('foo');
                var ids = eval('(' + this.responseText + ')');
                if (ids.length > 0) {
                    ids.reverse();
                    //window.href = ids[0];
                    alert(ids[0]);
                } else {
                    alert('No stories found.');
                }
            }
        });
    
        http.send();
    //})();
    

    这和预期的一样。(它利用 a little file 在节点中模拟XMLHttpRequest。)

    取消对函数定义行的注释(并删除其他node js内容)给了我一个很好的一行代码,一次 packed :

    javascript:(function(){url='http://api.ihackernews.com/getid?url='+encodeURIComponent(window.location.href);http=new XMLHttpRequest();http.open("GET",url,true);http.onreadystatechange=(function(){if(this.readyState==4){alert('foo');var ids=eval('('+this.responseText+')');if(ids.length>0){window.href=ids[0]}else{alert('No stories found.')}}});http.send()})();
    

    但是,运行它会提示Firefox的错误控制台给我一条非常有用的消息“语法错误”,然后是一个“()”错误,指向第二个括号的右边。

    我没有使用Firebug,因为它的nightly和Firefox的nightly现在不想合作。

    解决这个问题的办法可能很快就会找到(通常我是从解释文本框中的所有内容的过程中找到的),但我想我会很感激在这方面的任何帮助。我真的很烦。:/

    1 回复  |  直到 14 年前
        1
  •  3
  •   Nick Craver    14 年前

    因为你的回答是空白的(因为 same origin policy )基本上就是这样:

    eval('()'); //SyntaxError: Unexpected token )
    

    如果有响应,则需要添加一个检查,如下所示:

    http.onreadystatechange = (function () {
        if (this.readyState == 4) {
            if(this.responseText) { //was the response empty?
              var ids = eval('(' + this.responseText + ')');
              if (ids.length > 0) {
                ids.reverse();
                window.href = ids[0];
              }
            } else {
                alert('No stories found.');
            }
        }
    });