순수 JavaScript는 양식없이 POST 데이터를 전송합니다.
양식없이 순수하게 JavaScript (jQuery $.post()
아님) 만 사용하여 페이지를 새로 고치지 않고 POST 메서드를 사용하여 데이터를 개인 정보 처리 방침이 사용합니까? 어쩌면 또는 다른 것 (지금은 박물관 httprequest
수 없습니다)?
이를 전송하고 본문에 데이터를 삽입 할 수 있습니다.
var xhr = new XMLHttpRequest();
xhr.open("POST", yourUrl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: value
}));
그건 그렇고, 요청을 시티하려면 :
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();
XMLHttpRequest
다음과 같이 개체를 사용할 수 있습니다 .
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);
코드는에 해당 게시 someStuff
됩니다 url
. XMLHttpRequest
개체 를 만들 때 브라우저 간 호환이 가능한지 확인하십시오. 이를 수행하는 방법에 대한 끝없는 예가 있습니다.
[2017 년 작성 예정 최신 버전] Fetch API 는 GET 요청을 쉽게 만들기위한 것이지만 POST도 가능합니다.
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
나처럼 게 으르거나 바로 가기 / 도우미를 선호하는 경우 :
window.post = function(url, data) {
return fetch(url, {method: "POST", body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});
또한 RESTful을 사용하면 POST 요청 에서 데이터를 다시 찾을 수 있습니다 .
JS (Python을 통해 제공되는 비용 정적 / hello.html에 입력) :
<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>
Python 서버 (테스트 용) :
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)
콘솔 로그 (Chrome) :
HELLO
hello.html:14 {"req": {"value": "value"}}
hello.html:16
{req: {…}}
req
:
{value: "value"}
__proto__
:
Object
콘솔 로그 (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 }
콘솔 로그 (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"
}
}
Python 로그 :
HTTP 8/postman[post]: PATH='/postman'
URL 8/postman[post]: request data = {"value":"value"}
URL 8/postman[post]: response data = {"req": {"value": "value"}}
navigator.sendBeacon ()
당신은 필요한 경우 데이터와 서버의 응답을 필요로하지 않는 것, 가장 짧은 솔루션을 사용하는 것입니다 :POST
navigator.sendBeacon()
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);
참고 URL : https://stackoverflow.com/questions/6396101/pure-javascript-send-post-data-without-a-form
'IT' 카테고리의 다른 글
Pandas : Excel 파일에서 시트 목록 조회 (0) | 2020.08.20 |
---|---|
포드 컨테이너 내에서 Kubernetes API에 액세스해야합니까? (0) | 2020.08.20 |
three.js가있는 투명한 배경 (0) | 2020.08.20 |
자바의 긴 if 문 목록 (0) | 2020.08.20 |
CMake를 사용하여 C ++ 프로그램을 Boost와 연결하는 방법 (0) | 2020.08.20 |