我正在尝试使用 Rails 创建一个简单的书签,它使用当前页面标题和 URL 创建一个表单并提交以创建一个对象。
我遇到的问题是,当表单提交时,它会转发到“成功”页面,而不是仅仅停留在应有的页面上。
我知道小书签代码应该返回 undefined 以阻止这种情况发生,但我已经尝试将 void(0) 放在我能想到的任何地方,但它仍然会转到下一页。
以下是我尝试过的两种方法:
javascript:void((function(){
var s = document.createElement('script');
s.setAttribute('language','javascript');
s.setAttribute('src','http://localhost:3000/script/bookmarklet.js');
document.body.appendChild(s);
})());
和:
javascript:(function(){
var s = document.createElement('script');
s.setAttribute('language','javascript');
s.setAttribute('src','http://localhost:3000/script/bookmarklet.js');
document.body.appendChild(s);
void(0);
})();
其他 .js 文件是否会导致问题?在这里:
(function() {
function create_form() {
var path = "http://localhost:3000/links";
var newform = document.createElement('form');
newform.setAttribute("method", "post");
newform.setAttribute("action", path);
newform.setAttribute("accept-charset","UTF-8");
var title_hidden_field = document.createElement("input");
title_hidden_field.setAttribute("type","hidden");
title_hidden_field.setAttribute("name", "link[title]");
title_hidden_field.setAttribute("value", "Test Title");
newform.appendChild(title_hidden_field);
var url_hidden_field = document.createElement("input");
url_hidden_field.setAttribute("type","hidden");
url_hidden_field.setAttribute("name", "link[url]");
url_hidden_field.setAttribute("value", "http://www.example.com");
newform.appendChild(url_hidden_field);
document.body.appendChild(newform);
newform.submit();
};
create_form();
})();
我也尝试在那里返回 undefined,但转发行为没有改变。这可能与 Rails 处理表单发布请求的方式有关吗?
最佳答案
首先,void(0) 用于获取未定义的返回值,这是停止转到下一页的一种方法,但不适用于此处。此外,请确保在小书签的末尾保留 void(0)。
我认为停止进入下一页的一种方法是首先创建一个不可见的内联框架(iframe)
var myiframe = document.createElement('iframe');
myiframe.scrolling = "no";
myiframe.name = "myiframe";
myiframe.id = "myiframe";
myiframe.src = "blank.html"; //so your users wont have to use their bandwith much, I think you can also set it to the about page in many browsers
myiframe.width = "0px"; //so it becomes invisible
myiframe.height = "0px"; //""
document.body.appendChild(myiframe)
或
var ThisBody = document.body.innerHTML
ThisBody += '<iframe frameborder="0" scrolling="no" name="myiframe" id="myiframe" src="blank.html" width="0px" height="0px"></iframe>
然后通过使用目标设置你的新表单,这是这里最重要的部分:
newform.target = "document.getElementById('myiframe')" //our iframe
我想就是这样。
还有:
javascript:(function(){
var s = document.createElement('script');
s.setAttribute('language','javascript');
s.setAttribute('src','http://localhost:3000/script/bookmarklet.js');
document.body.appendChild(s);
})();void(0)
那是 void 应该去的地方 ^^
关于javascript - 在小书签中返回未定义 - 转发页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6418928/