Esiste un modo per inviare dati utilizzando il metodo POST senza un modulo e senza aggiornare la pagina utilizzando solo JavaScript puro (non jQuery $.post())? Forse httprequesto qualcos'altro (non riesco a trovarlo ora)?
Esiste un modo per inviare dati utilizzando il metodo POST senza un modulo e senza aggiornare la pagina utilizzando solo JavaScript puro (non jQuery $.post())? Forse httprequesto qualcos'altro (non riesco a trovarlo ora)?
Risposte:
Puoi inviarlo e inserire i dati nel corpo:
var xhr = new XMLHttpRequest();
xhr.open("POST", yourUrl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: value
}));
A proposito, per ottenere la richiesta:
var xhr = new XMLHttpRequest();
// we defined the xhr
xhr.onreadystatechange = function () {
if (this.readyState != 4) return;
if (this.status == 200) {
var data = JSON.parse(this.responseText);
// we get the returned data
}
// end of state change: it can be after some time (async)
};
xhr.open('GET', yourUrl, true);
xhr.send();
L' API Fetch [new-ish al momento in cui scrivo nel 2017] ha lo scopo di semplificare le richieste GET, ma è anche in grado di postare.
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
Se sei pigro come me (o preferisci semplicemente una scorciatoia / aiuto):
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});
È possibile utilizzare l' XMLHttpRequestoggetto come segue:
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);
Quel codice verrà inviato someStuffa url. Assicurati solo che quando crei il tuo XMLHttpRequestoggetto, sia compatibile con più browser. Ci sono infiniti esempi là fuori di come farlo.
someStuff?
someStuffpuò essere qualsiasi cosa tu voglia anche una semplice stringa. puoi controllare la richiesta usando servizi online come il mio preferito: ( requestb.in )
application/x-www-form-urlencodedtipo MIME non ha un charsetparametro: iana.org/assignments/media-types/application/…
Inoltre, RESTful consente di ottenere i dati indietro da un POST richiesta.
JS (messo in static / hello.html per servire tramite Python):
<html><head><meta charset="utf-8"/></head><body>
Hello.
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "/postman", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: 'value'
}));
xhr.onload = function() {
console.log("HELLO")
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log(data);
}
</script></body></html>
Server Python (per test):
import time, threading, socket, SocketServer, BaseHTTPServer
import os, traceback, sys, json
log_lock = threading.Lock()
log_next_thread_id = 0
# Local log functiondef
def Log(module, msg):
with log_lock:
thread = threading.current_thread().__name__
msg = "%s %s: %s" % (module, thread, msg)
sys.stderr.write(msg + '\n')
def Log_Traceback():
t = traceback.format_exc().strip('\n').split('\n')
if ', in ' in t[-3]:
t[-3] = t[-3].replace(', in','\n***\n*** In') + '(...):'
t[-2] += '\n***'
err = '\n*** '.join(t[-3:]).replace('"','').replace(' File ', '')
err = err.replace(', line',':')
Log("Traceback", '\n'.join(t[:-3]) + '\n\n\n***\n*** ' + err + '\n***\n\n')
os._exit(4)
def Set_Thread_Label(s):
global log_next_thread_id
with log_lock:
threading.current_thread().__name__ = "%d%s" \
% (log_next_thread_id, s)
log_next_thread_id += 1
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
Set_Thread_Label(self.path + "[get]")
try:
Log("HTTP", "PATH='%s'" % self.path)
with open('static' + self.path) as f:
data = f.read()
Log("Static", "DATA='%s'" % data)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(data)
except:
Log_Traceback()
def do_POST(self):
Set_Thread_Label(self.path + "[post]")
try:
length = int(self.headers.getheader('content-length'))
req = self.rfile.read(length)
Log("HTTP", "PATH='%s'" % self.path)
Log("URL", "request data = %s" % req)
req = json.loads(req)
response = {'req': req}
response = json.dumps(response)
Log("URL", "response data = %s" % response)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
except:
Log_Traceback()
# Create ONE socket.
addr = ('', 8000)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
sock.listen(5)
# Launch 100 listener threads.
class Thread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
self.daemon = True
self.start()
def run(self):
httpd = BaseHTTPServer.HTTPServer(addr, Handler, False)
# Prevent the HTTP server from re-binding every handler.
# https://stackoverflow.com/questions/46210672/
httpd.socket = sock
httpd.server_bind = self.server_close = lambda self: None
httpd.serve_forever()
[Thread(i) for i in range(10)]
time.sleep(9e9)
Registro console (cromato):
HELLO
hello.html:14 {"req": {"value": "value"}}
hello.html:16
{req: {…}}
req
:
{value: "value"}
__proto__
:
Object
Registro console (firefox):
GET
http://XXXXX:8000/hello.html [HTTP/1.0 200 OK 0ms]
POST
XHR
http://XXXXX:8000/postman [HTTP/1.0 200 OK 0ms]
HELLO hello.html:13:3
{"req": {"value": "value"}} hello.html:14:3
Object { req: Object }
Registro console (Edge):
HTML1300: Navigation occurred.
hello.html
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "<!DOCTYPE html>".
hello.html (1,1)
Current window: XXXXX/hello.html
HELLO
hello.html (13,3)
{"req": {"value": "value"}}
hello.html (14,3)
[object Object]
hello.html (16,3)
{
[functions]: ,
__proto__: { },
req: {
[functions]: ,
__proto__: { },
value: "value"
}
}
Registro Python:
HTTP 8/postman[post]: PATH='/postman'
URL 8/postman[post]: request data = {"value":"value"}
URL 8/postman[post]: response data = {"req": {"value": "value"}}
Esiste un metodo semplice per racchiudere i dati e inviarli al server come se si stesse inviando un modulo HTML tramite POST. puoi farlo usando l' FormDataoggetto come segue:
data = new FormData()
data.set('Foo',1)
data.set('Bar','boo')
let request = new XMLHttpRequest();
request.open("POST", 'some_url/', true);
request.send(data)
ora è possibile gestire i dati sul lato server proprio come nel modo in cui si gestiscono i moduli HTML ridondanti.
Informazioni addizionali
Si consiglia di non impostare l'intestazione Content-Type quando si invia FormData poiché il browser se ne occuperà.
FormDatacreerà una richiesta di modulo multipart piuttosto che una application/x-www-form-urlencodedrichiesta
Se hai semplicemente bisogno di POSTdati e non richiedi una risposta dal server, la soluzione più breve sarebbe quella di usare navigator.sendBeacon():
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);
navigator.sendBeacona mio avviso, non è pensato per essere utilizzato a questo scopo.
Puoi usare XMLHttpRequest, recuperare l'API, ...
Se vuoi usare XMLHttpRequest puoi fare quanto segue
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: "Deska",
email: "deska@gmail.com",
phone: "342234553"
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log(data);
};
O se vuoi usare l'API di recupero
fetch(url, {
method:"POST",
body: JSON.stringify({
name: "Deska",
email: "deska@gmail.com",
phone: "342234553"
})
})
.then(result => {
// do something with the result
console.log("Completed with result:", result);
});
Sapevi che JavaScript ha i suoi metodi e librerie integrati per creare moduli e inviarli?
Sto vedendo molte risposte qui tutte che chiedono di utilizzare una libreria di terze parti che penso sia eccessiva.
Vorrei fare quanto segue in puro Javascript:
<script>
function launchMyForm()
{
var myForm = document.createElement("FORM");
myForm.setAttribute("id","TestForm");
document.body.appendChild(myForm);
// this will create a new FORM which is mapped to the Java Object of myForm, with an id of TestForm. Equivalent to: <form id="TestForm"></form>
var myInput = document.createElement("INPUT");
myInput.setAttribute("id","MyInput");
myInput.setAttribute("type","text");
myInput.setAttribute("value","Heider");
document.getElementById("TestForm").appendChild(myInput);
// This will create an INPUT equivalent to: <INPUT id="MyInput" type="text" value="Heider" /> and then assign it to be inside the TestForm tags.
}
</script>
In questo modo (A) non è necessario fare affidamento su terze parti per svolgere il lavoro. (B) È tutto integrato in tutti i browser, (C) più veloce, (D) funziona, sentiti libero di provarlo.
Spero che aiuti. H