Am'm încercarea de a direcționa un browser la o altă pagină. Dacă am vrut o cerere, am putea spune
document.location.href = 'http://example.com/q=a';
Dar resursa I'm încercat să acceseze câștigat't răspunde în mod corespunzător dacă nu utilizați o cerere POST. Dacă acest lucru nu au fost generate dinamic, s-ar putea folosi HTML
<form action="http://example.com/" method="POST">
<input type="hidden" name="q" value="a">
</form>
Și atunci mi-ar depune formularul din DOM.
Dar chiar aș dori un cod JavaScript care permite-mi să spun
post_to_url('http://example.com/', {'q':'a'});
Ce's cel mai bun browser-ul cruce de implementare?
Edit
Am'm rău că nu am fost clar. Am nevoie de o soluție care să schimbe locul de browser-ul, doar ca trimiterea unui formular. Dacă acest lucru este posibil cu XMLHttpRequest, nu este evident. Și acest lucru nu ar trebui să fie asincron, nici să-l utilizați XML, astfel încât Ajax nu este răspunsul.
``js /**
funcția de post(cale, params, metoda='post') {
// Restul codului presupune nu utilizați o bibliotecă. // Acesta poate fi făcut mai puțin prolix dacă utilizați unul. const form = de document.createElement('forma'); forma.metoda = metoda; forma.acțiune = cale;
pentru (const cheie în params) { dacă (params.hasOwnProperty(cheie)) { const hiddenField = document.createElement('de intrare'); hiddenField.tip = 'ascuns'; hiddenField.name = cheie; hiddenField.valoare = params[cheie];
forma.appendChild(hiddenField); } }
document.corpul.appendChild(formular); forma.submit(); }
``
Exemplu:
js post('/contact/', {nume: 'Johnny Bravo'});
EDIT: Deoarece aceasta a ajuns upvoted atât de mult, am'm a ghici ce va fi copiere-lipire mult la asta. Așa că am adăugat `hasOwnProperty de verificare pentru a rezolva orice accidental bug-uri.
Aceasta ar fi o versiune de răspunsul selectat folosind 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();
}
Un simplu-rapid și-murdar punerea în aplicare a @Aaron a răspuns:
document.body.innerHTML += '<form id="dynForm" action="http://example.com/" method="post"><input type="hidden" name="q" value="a"></form>';
document.getElementById("dynForm").submit();
Desigur, mai degrabă ar trebui să utilizați un cadru JavaScript, cum ar fi Prototip sau jQuery...
Folosind createElement funcția prevăzută în [acest răspuns][1], care este necesar din cauza [IE's zdrobire cu atributul name][2] pe elemente create în mod normal cu 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's a răspunde este uimitor, dar există o problemă care apare pentru mine (de Mozilla), atunci când am încercați pentru a posta un formular cu un câmp numit "trimite". De exemplu, post_to_url("http://google.com/",{ prezinte: "trimiteți" } );
. Am patch-uri în funcție de ușor pentru a merge în jurul acestui spațiu variabil de coliziune.
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!
Nr. Puteți't au JavaScript cerere post ca o formă prezinte.
Ce este un formular in HTML, apoi trimite-l cu JavaScript. (așa cum sa explicat de multe ori pe această pagină).
Puteți crea HTML-te, nu't nevoie de JavaScript pentru a scrie HTML. Ar fi o prostie dacă oamenii au sugerat că.
<form id="ninja" action="http://example.com/" method="POST">
<input id="donaldduck" type="hidden" name="q" value="a">
</form>
Funcția ta ar configura forma așa cum vă doriți.
function postToURL(a,b,c){
document.getElementById("ninja").action = a;
document.getElementById("donaldduck").name = b;
document.getElementById("donaldduck").value = c;
document.getElementById("ninja").submit();
}
Apoi, utilizați-l ca.
postToURL("http://example.com/","q","a");
Dar mi-ar părăsi funcția și nu doar.
document.getElementById('donaldduck').value = "a";
document.getElementById("ninja").submit();
În cele din urmă, decizia de stil merge în scc fișier.
#ninja{
display:none;
}
Personal cred forme ar trebui să fie abordate cu numele dar nu asta e important acum.
Dacă aveți Prototip instalat, puteți strânge de cod pentru a genera și transmite formă ascunsă de genul asta:
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();
acesta este răspunsul de rakesh, dar cu suport pentru tablouri (care este destul de comună în forme):
simplu 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();
}
oh, și aici's jquery versiune: (ușor diferite de cod, dar se reduce la același lucru)
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();
}
O soluție este de a genera formularul și trimiteți-l. O singură aplicare este
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();
}
Așa că am putea pune în aplicare o scurtare URL bookmarklet cu un simplu
javascript:post_to_url('http://is.gd/create.php', {'URL': location.href});
Ei bine, aș dori să am citit toate celelalte posturi, așa că m-am't pierde timpul crearea acestui din Rakesh Pai's a răspunde. Aici's o recursive soluție care funcționează cu tablouri și obiecte. Nici o dependență pe jQuery.
Adăugat un segment să se ocupe de cazurile în care întreaga formă ar trebui să fie prezentate ca o matrice. (de exemplu. în cazul în care nu's nici un obiect înveliș în jurul valorii de o listă de articole)
/**
* 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();
};
Aici este cum am scris-o folosind jQuery. Testat în Firefox și Internet Explorer.
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();
}
Am'd du-te jos la Ajax traseu ca alții au sugerat cu ceva de genul:
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");
Trei opțiuni de aici.
Standard JavaScript răspuns: Utilizați un cadru! Cele mai Ajax cadre va fi captată o modalitate ușoară de a face un XMLHTTPRequest POST.
Face XMLHTTPRequest cerere, trecerea post în metoda deschisă în loc de a obține. (Mai multe informații în Folosind metoda POST în XMLHTTPRequest (Ajax).)
Prin intermediul JavaScript, dinamic crea un formular, adăugați o acțiune, adăugați intrări, și susțin că.
Cel mai simplu mod este folosind Ajax Cerere Post:
$.ajax({
type: "POST",
url: 'http://www.myrestserver.com/api',
data: data,
success: success,
dataType: dataType
});
în cazul în care:
Apoi, în succesul handler redirecționa browser-ul cu ceva de genul fereastră.locație.
De Prototip biblioteca include un Hashtable obiect, cu o ".toQueryString()" metodă, care vă permite să transforma cu ușurință un obiect JavaScript/structura intr-un query-string stil șir. De post necesită "body" de cererea de a fi un query-string string formatat, acest lucru permite Ajax cerere pentru a funcționa în mod corespunzător ca un post. Aici's un exemplu folosind Prototipul:
$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();
};
Aceasta funcționează perfect în cazul meu:
document.getElementById("form1").submit();
Puteți să-l utilizați în funcție, cum ar fi:
function formSubmit() {
document.getElementById("frmUserList").submit();
}
Folosind aceasta, puteți posta toate valorile factorilor de producție.
Soluția mea va codifica profund imbricate obiecte, spre deosebire de cea acceptată în prezent soluție de @RakeshPai.
Se folosește 'qs' npm bibliotecă și stringify funcție pentru a converti obiecte imbricate în parametri.
Acest cod funcționează bine cu Șine de back-end, deși ar trebui să fie capabil să-l modifice pentru a lucra cu orice backend ai nevoie de modificarea opțiuni trecut la stringify. Șine impune ca arrayFormat fi setat la "console".
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();
}
Exemplu:
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"]
}
]
});
Produce aceste Șine parametri:
{"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"]}]}
Încă un alt recursive soluție, deoarece unele de altele par a fi rupt (am n't test tot de pe ei). Asta depinde lodash 3.x și ES6 (jQuery nu este obligatoriu):
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();
}