我正在尝试将浏览器指向另一个页面。如果我想要GET请求,我可以说
document.location.href = 'http://example.com/q=a';
但是,除非我使用POST请求,否则我试图访问的资源将无法正确响应。如果这不是动态生成的,我可能会使用HTML
<form action="http://example.com/" method="POST">
<input type="hidden" name="q" value="a">
</form>
然后我只需从DOM提交表单。
但实际上,我希望JavaScript代码能够让我说
post_to_url('http://example.com/', {'q':'a'});
最好的跨浏览器实现是什么?
我需要一个改变浏览器位置的解决方案,就像提交表单一样。这不应该是异步的,也不应该使用XML,因此Ajax不是答案。
这是rakesh的答案,但支持数组(这在形式上很常见):
纯javascript:
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
var addField = function( key, value ){
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value );
form.appendChild(hiddenField);
};
for(var key in params) {
if(params.hasOwnProperty(key)) {
if( params[key] instanceof Array ){
for(var i = 0; i < params[key].length; i++){
addField( key, params[key][i] )
}
}
else{
addField( key, params[key] );
}
}
}
document.body.appendChild(form);
form.submit();
}
哦,这里是jquery版本:(代码略有不同,但归结起来是相同的)
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = $(document.createElement( "form" ))
.attr( {"method": method, "action": path} );
$.each( params, function(key,value){
$.each( value instanceof Array? value : [value], function(i,val){
$(document.createElement("input"))
.attr({ "type": "hidden", "name": key, "value": val })
.appendTo( form );
});
} );
form.appendTo( document.body ).submit();
}
这是基于beauSD使用jQuery的代码。它得到了改进,因此可以递归地处理对象。
function post(url, params, urlEncoded, newWindow) {
var form = $('<form />').hide();
form.attr('action', url)
.attr('method', 'POST')
.attr('enctype', urlEncoded ? 'application/x-www-form-urlencoded' : 'multipart/form-data');
if(newWindow) form.attr('target', '_blank');
function addParam(name, value, parent) {
var fullname = (parent.length > 0 ? (parent + '[' + name + ']') : name);
if(value instanceof Object) {
for(var i in value) {
addParam(i, value[i], fullname);
}
}
else $('<input type="hidden" />').attr({name: fullname, value: value}).appendTo(form);
};
addParam('', params, '');
$('body').append(form);
form.submit();
}
Prototype库包含一个Hashtable对象和一个“.toQueryString()”方法,它允许您轻松地将JavaScript对象/结构转换为查询字符串样式的字符串。由于post要求请求的“主体”是查询字符串格式的字符串,这允许Ajax请求作为post正常工作。以下是使用原型的示例:
$req = new Ajax.Request("http://foo.com/bar.php",{
method: 'post',
parameters: $H({
name: 'Diodeus',
question: 'JavaScript posts a request like a form request',
...
}).toQueryString();
};
还有另一个递归解决方案,因为其他一些似乎已被破坏(我没有测试所有这些)。这取决于lodash 3.x和ES6(不需要jQuery):
function createHiddenInput(name, value) {
let input = document.createElement('input');
input.setAttribute('type','hidden');
input.setAttribute('name',name);
input.setAttribute('value',value);
return input;
}
function appendInput(form, name, value) {
if(_.isArray(value)) {
_.each(value, (v,i) => {
appendInput(form, `${name}[${i}]`, v);
});
} else if(_.isObject(value)) {
_.forOwn(value, (v,p) => {
appendInput(form, `${name}[${p}]`, v);
});
} else {
form.appendChild(createHiddenInput(name, value));
}
}
function postToUrl(url, data) {
let form = document.createElement('form');
form.setAttribute('method', 'post');
form.setAttribute('action', url);
_.forOwn(data, (value, name) => {
appendInput(form, name, value);
});
form.submit();
}
不可以。您不能像提交表单一样提交JavaScript发布请求。
您可以拥有HTML格式的表单,然后使用JavaScript提交它。(如本页多次所述)。
您可以自己创建HTML,不需要JavaScript来编写HTML。如果有人这样建议,那就太傻了。
<form id="ninja" action="http://example.com/" method="POST">
<input id="donaldduck" type="hidden" name="q" value="a">
</form>
您的函数将按照您想要的方式配置表单。
function postToURL(a,b,c){
document.getElementById("ninja").action = a;
document.getElementById("donaldduck").name = b;
document.getElementById("donaldduck").value = c;
document.getElementById("ninja").submit();
}
然后,像这样使用它。
postToURL("http://example.com/","q","a");
但我会省略函数,只做。
document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();
最后,样式决定在ccs文件中。
#ninja {
display: none;
}
就我个人而言,我认为表格应该用名字来称呼,但现在这并不重要。