JavaScript员额的请求等形式提交
-
02-07-2019 - |
题
我想直接浏览器的一个不同的网页。如果我想要一个获得请求,我可能会说
document.location.href = 'http://example.com/q=a';
但是资源,我试图访问不作出适当反应,除非我用一个员额的请求。如果这是不会动态产生的,我可能会使用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,所以阿贾克斯不是答案。
解决方案
在表单中动态创建<input>
并提交
/**
* sends a request to the specified url from a form. this will change the window location.
* @param {string} path the path to send the post request to
* @param {object} params the paramiters to add to the url
* @param {string} [method=post] the method to use on the form
*/
function post(path, params, method='post') {
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
const form = document.createElement('form');
form.method = method;
form.action = path;
for (const key in params) {
if (params.hasOwnProperty(key)) {
const hiddenField = document.createElement('input');
hiddenField.type = 'hidden';
hiddenField.name = key;
hiddenField.value = params[key];
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
示例:
post('/contact/', {name: 'Johnny Bravo'});
编辑:由于这已经引起了如此多的关注,我猜测人们将会复制粘贴这么多。所以我添加了hasOwnProperty
检查以修复任何无意的错误。
其他提示
这将是使用 jQuery 所选答案的一个版本。
// Post to the provided URL with the specified parameters.
function post(path, parameters) {
var form = $('<form></form>');
form.attr("method", "post");
form.attr("action", path);
$.each(parameters, function(key, value) {
var field = $('<input></input>');
field.attr("type", "hidden");
field.attr("name", key);
field.attr("value", value);
form.append(field);
});
// The form needs to be a part of the document in
// order for us to be able to submit it.
$(document.body).append(form);
form.submit();
}
使用createElement功能works-in-all-br#120372“>这个答案,这是必要的,因为 IE通常使用document.createElement
创建的元素的名称属性为:
function postToURL(url, values) {
values = values || {};
var form = createElement("form", {action: url,
method: "POST",
style: "display: none"});
for (var property in values) {
if (values.hasOwnProperty(property)) {
var value = values[property];
if (value instanceof Array) {
for (var i = 0, l = value.length; i < l; i++) {
form.appendChild(createElement("input", {type: "hidden",
name: property,
value: value[i]}));
}
}
else {
form.appendChild(createElement("input", {type: "hidden",
name: property,
value: value}));
}
}
}
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
}
Rakesh Pai的回答很棒,但是当我尝试发布时,我遇到了一个问题(在 Safari 中)带有名为submit
的字段的表单。例如,post_to_url("http://google.com/",{ submit: "submit" } );
。我稍微修补了这个函数以绕过这个变量空间碰撞。
function post_to_url(path, params, method) {
method = method || "post";
var form = document.createElement("form");
//Move the submit function to another variable
//so that it doesn't get overwritten.
form._submit_function_ = form.submit;
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form._submit_function_(); //Call the renamed function.
}
post_to_url("http://google.com/", { submit: "submit" } ); //Works!
没有。您不能像表单提交那样拥有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;
}
我个人认为表格应该通过名字来解决,但现在这并不重要。
如果您安装了原型,则可以收紧代码以生成并提交隐藏的表单,如下所示:
var form = new Element('form',
{method: 'post', action: 'http://example.com/'});
form.insert(new Element('input',
{name: 'q', value: 'a', type: 'hidden'}));
$(document.body).insert(form);
form.submit();
这是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();
}
一种解决方案是生成表单并提交。一个实现是
function post_to_url(url, params) {
var form = document.createElement('form');
form.action = url;
form.method = 'POST';
for (var i in params) {
if (params.hasOwnProperty(i)) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = i;
input.value = params[i];
form.appendChild(input);
}
}
form.submit();
}
所以我可以用简单的
实现一个URL缩短书签javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});
嗯,希望我已经阅读了所有其他帖子,所以我没有浪费时间从Rakesh Pai的回答中创造这个。这是一个适用于数组和对象的递归解决方案。不依赖于jQuery。
添加了一个段来处理整个表单应该像数组一样提交的情况。 (即,项目列表周围没有包装器对象)
/**
* Posts javascript data to a url using form.submit().
* Note: Handles json and arrays.
* @param {string} path - url where the data should be sent.
* @param {string} data - data as javascript object (JSON).
* @param {object} options -- optional attributes
* {
* {string} method: get/post/put/etc,
* {string} arrayName: name to post arraylike data. Only necessary when root data object is an array.
* }
* @example postToUrl('/UpdateUser', {Order {Id: 1, FirstName: 'Sally'}});
*/
function postToUrl(path, data, options) {
if (options === undefined) {
options = {};
}
var method = options.method || "post"; // Set method to post by default if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
function constructElements(item, parentString) {
for (var key in item) {
if (item.hasOwnProperty(key) && item[key] != null) {
if (Object.prototype.toString.call(item[key]) === '[object Array]') {
for (var i = 0; i < item[key].length; i++) {
constructElements(item[key][i], parentString + key + "[" + i + "].");
}
} else if (Object.prototype.toString.call(item[key]) === '[object Object]') {
constructElements(item[key], parentString + key + ".");
} else {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", parentString + key);
hiddenField.setAttribute("value", item[key]);
form.appendChild(hiddenField);
}
}
}
}
//if the parent 'data' object is an array we need to treat it a little differently
if (Object.prototype.toString.call(data) === '[object Array]') {
if (options.arrayName === undefined) console.warn("Posting array-type to url will doubtfully work without an arrayName defined in options.");
//loop through each array item at the parent level
for (var i = 0; i < data.length; i++) {
constructElements(data[i], (options.arrayName || "") + "[" + i + "].");
}
} else {
//otherwise treat it normally
constructElements(data, "");
}
document.body.appendChild(form);
form.submit();
};
这里有三个选择。
-
标准JavaScript答案:使用框架!大多数Ajax框架都会让您轻松地制作 XMLHTTPRequest POST。
-
自己制作XMLHTTPRequest请求,将post传递给open方法而不是get。 ( 在XMLHTTPRequest(Ajax)中使用POST方法的更多信息 。)
-
通过JavaScript,动态创建表单,添加操作,添加输入并提交输入。
醇>
我会像其他人建议的那样沿着Ajax路线前进:
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open("POST", "YourPageHere.asp", true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
self.xmlHttpReq.setRequestHeader("Content-length", QueryString.length);
self.xmlHttpReq.send("?YourQueryString=Value");
以下是我使用jQuery编写的方法。在Firefox和Internet <!>资源管理器中测试。
function postToUrl(url, params, newWindow) {
var form = $('<form>');
form.attr('action', url);
form.attr('method', 'POST');
if(newWindow){ form.attr('target', '_blank');
}
var addParam = function(paramName, paramValue) {
var input = $('<input type="hidden">');
input.attr({ 'id': paramName,
'name': paramName,
'value': paramValue });
form.append(input);
};
// Params is an Array.
if(params instanceof Array){
for(var i=0; i<params.length; i++) {
addParam(i, params[i]);
}
}
// Params is an Associative array or Object.
if(params instanceof Object) {
for(var key in params){
addParam(key, params[key]);
}
}
// Submit the form, then remove it from the page
form.appendTo(document.body);
form.submit();
form.remove();
}
最简单的方法是使用的Ajax员额的请求:
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success,
dataType: dataType
});
其中:
- 数据是一个对象
- 据类型的数据,预计通过服务器(xml, 式,脚本、中文本、html)
- url地址是你的休息服务器或任何功能的服务器上面,接受HTTP员额。
然后在成功的处理程序向浏览器喜欢的东西窗口。位置。
Prototype 库包含一个Hashtable对象,带有<!> quot; .toQueryString <!>()QUOT;方法,它允许您轻松地将JavaScript对象/结构转换为查询字符串样式字符串。由于帖子需要<!>“body <!>”;请求是一个查询字符串格式的字符串,这允许您的Ajax请求作为一个帖子正常工作。以下是使用Prototype的示例:
$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();
};
这完全适用于我的情况:
document.getElementById("form1").submit();
您可以在以下功能中使用它:
function formSubmit() {
document.getElementById("frmUserList").submit();
}
使用此功能,您可以发布所有输入值。
FormObject 是一个选项。但是现在大多数浏览器都不支持FormObject。
又一个递归解决方案,因为其他一些似乎被破坏了(我没有测试所有这些)。这个取决于 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();
}
我的解决方案将对深层嵌套对象进行编码,这与@RakeshPai当前接受的解决方案不同。
它使用'qs'npm库及其stringify函数将嵌套对象转换为参数。
此代码适用于Rails后端,但您应该能够通过修改传递给stringify的选项来修改它以使用您需要的任何后端。 Rails要求将arrayFormat设置为<!> quot;括号<!>“;
import qs from "qs"
function normalPost(url, params) {
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", url);
const keyValues = qs
.stringify(params, { arrayFormat: "brackets", encode: false })
.split("&")
.map(field => field.split("="));
keyValues.forEach(field => {
var key = field[0];
var value = field[1];
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", value);
form.appendChild(hiddenField);
});
document.body.appendChild(form);
form.submit();
}
示例:
normalPost("/people/new", {
people: [
{
name: "Chris",
address: "My address",
dogs: ["Jordan", "Elephant Man", "Chicken Face"],
information: { age: 10, height: "3 meters" }
},
{
name: "Andrew",
address: "Underworld",
dogs: ["Doug", "Elf", "Orange"]
},
{
name: "Julian",
address: "In a hole",
dogs: ["Please", "Help"]
}
]
});
生成这些Rails参数:
{"authenticity_token"=>"...",
"people"=>
[{"name"=>"Chris", "address"=>"My address", "dogs"=>["Jordan", "Elephant Man", "Chicken Face"], "information"=>{"age"=>"10", "height"=>"3 meters"}},
{"name"=>"Andrew", "address"=>"Underworld", "dogs"=>["Doug", "Elf", "Orange"]},
{"name"=>"Julian", "address"=>"In a hole", "dogs"=>["Please", "Help"]}]}
这就像Alan的选项2(上图)。如何实例化httpobj作为一个练习。
httpobj.open("POST", url, true);
httpobj.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
httpobj.onreadystatechange=handler;
httpobj.send(post);
这是基于使用jQuery的beauSD代码。它得到了改进,因此它可以在对象上递归工作。
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();
}
您可以使用DHTML动态添加表单,然后提交。
你可以使用像jQuery这样的库及其 $ .post方法。
我使用document.forms java并将其循环以获取表单中的所有元素,然后通过xhttp发送。所以这是我的javascript / ajax提交解决方案(以所有html为例):
<!DOCTYPE html>
<html>
<body>
<form>
First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
Addr1: <input type="text" name="add" value="123 Pond Dr"><br>
City: <input type="text" name="city" value="Duckopolis"><br>
</form>
<button onclick="smc()">Submit</button>
<script>
function smc() {
var http = new XMLHttpRequest();
var url = "yourphpfile.php";
var x = document.forms[0];
var xstr = "";
var ta ="";
var tb ="";
var i;
for (i = 0; i < x.length; i++) {
if (i==0){ta = x.elements[i].name+"="+ x.elements[i].value;}else{
tb = tb+"&"+ x.elements[i].name +"=" + x.elements[i].value;
} }
xstr = ta+tb;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// do whatever you want to with the html output response here
}
}
http.send(xstr);
}
</script>
</body>
</html>
我用来自动发布和引导用户到另一个页面的方法是只写一个隐藏的表单,然后自动提交它。请放心,隐藏的表单在网页上绝对没有空间。代码将是这样的:
<form name="form1" method="post" action="somepage.php">
<input name="fielda" type="text" id="fielda" type="hidden">
<textarea name="fieldb" id="fieldb" cols="" rows="" style="display:none"></textarea>
</form>
document.getElementById('fielda').value="some text for field a";
document.getElementById('fieldb').innerHTML="some text for multiline fieldb";
form1.submit();
自动提交的应用
自动提交的应用程序将指导用户自动放入另一页面的表单值返回该页面。这样的应用程序将是这样的:
fieldapost=<?php echo $_post['fielda'];>
if (fieldapost !="") {
document.write("<form name='form1' method='post' action='previouspage.php'>
<input name='fielda' type='text' id='fielda' type='hidden'>
</form>");
document.getElementById('fielda').value=fieldapost;
form1.submit();
}
我是这样做的。
function redirectWithPost(url, data){
var form = document.createElement('form');
form.method = 'POST';
form.action = url;
for(var key in data){
var input = document.createElement('input');
input.name = key;
input.value = data[key];
input.type = 'hidden';
form.appendChild(input)
}
document.body.appendChild(form);
form.submit();
}
jQuery插件,用于重定向POST或GET:
https://github.com/mgalante/jquery .redirect /斑点/主/ jquery.redirect.js
要测试,请包含上面的.js文件或将类复制/粘贴到您的代码中,然后在此处使用代码,替换<!> quot; args <!> quot;使用您的变量名称,以及<!> quot; values <!> quot;使用这些相应变量的值:
$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});
你可以使用jQuery触发器方法来提交表单,就像按下按钮一样,
$('form').trigger('submit')
它将在浏览器上提交。
您可以进行AJAX调用(可能使用诸如使用Prototype.js或JQuery之类的库)。 AJAX可以处理GET和POST选项。