用Javascript制作一个书签小工具

4
我正在尝试为我的网站制作一个书签工具。我已经制作了一个php页面,当发送一个GET请求时,例如www.website.com/index.html?a=banana,它将返回echo 'stand';
现在我正在尝试制作一个书签工具,当我按下它时,将执行GET到php页面,然后在小弹窗中显示回显给用户,并在3秒后消失。
我该怎么做?
Instapaper书签工具可以做到...
javascript:
function%20iprl5(){
  var%20d=document,z=d.createElement('scr'+'ipt'),b=d.body,l=d.location;
  try{
    if(!b)
      throw(0);
    d.title='(Saving...)%20'+d.title;
    z.setAttribute('src',l.protocol+'//www.instapaper.com/j/deyNbbpjuSei?u='+encodeURIComponent(l.href)+'&t='+(new%20Date().getTime()));
    b.appendChild(z);
  }
  catch(e){
    alert('Please%20wait%20until%20the%20page%20has%20loaded.');
  }
}
iprl5();
void(0)
1个回答

2
一个书签脚本是一段在你所在页面范围内运行的 JavaScript 代码。
它不是为了调用任意 URL 而存在的,因为这将违反“同源”规则。如果您的 PHP 可以返回 JSONP,则可以编写一个书签脚本,在页面上插入一个脚本,调用您返回的脚本 - 这将能够显示弹出窗口。
javascript:
function%20iprl5(){
  var%20d=document; // shorten document object
  var z=d.createElement('scr'+'ipt'); // create a script tag
  var b=d.body; // get document.body
  var l=d.location; // get document.location - I would get document.URL instead
  try{
    if(!b) throw(0); // if there is no body object available
    d.title='(Saving...)%20'+d.title; // set document.title
    z.setAttribute('src',l.protocol+'//www.yourserver.com/test.php?u='+encodeURIComponent(l.href)+'&time='+(new%20Date().getTime())); // create the script url
    b.appendChild(z); // append it to the body - I would append to head myself
  }
  catch(e){ // give an error
    alert('Please%20wait%20until%20the%20page%20has%20loaded.');
  }
}
iprl5(); // call it
void(0); // make sure it does not return a value to the window

将此代码view-source:http://www.instapaper.com/j/deyNbbpjuSei?u=http://www.stackoverflow.com粘贴到地址栏,以查看作为所在页面的一部分返回的内容数量。


如果这是真的,那Instapaper怎么做到的呢?他们提供了一个书签小工具,你点击它就可以实现这个功能... - David19801
我相信他们会按照我的建议去做。发一下书签并让我看看。Fancy也是这样做的。 - mplungjan
1
@david19801,Instapaper 可能是使用 JSONP,就像 @mplungjan 提到的那样。请了解 AJAX 和 JSONP! - BGerrissen
编辑:已删除评论。包含在mplungjan对帖子的更新中。 - Amitay Dobo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接