纯JavaScript在没有表单的情况下发送POST数据

时间:2011-06-18 12:46:39

标签: javascript post httpwebrequest xmlhttprequest http-post

有没有办法使用没有表单的POST方法发送数据,只使用纯JavaScript(不是jQuery $.post())刷新页面?也许httprequest或其他东西(现在找不到)?

12 个答案:

答案 0 :(得分:80)

您可以发送并将数据插入正文:

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();

答案 1 :(得分:48)

您可以按如下方式使用XMLHttpRequest对象:

xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);

该代码会将someStuff发布到url。只需确保在创建XMLHttpRequest对象时,它将与浏览器兼容。有无数的例子说明如何做到这一点。

答案 2 :(得分:23)

[2017年撰写时的新内容] Fetch API旨在让GET请求变得简单,但它也可以发布。

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"});

答案 3 :(得分:17)

此外,RESTful允许您从 POST 请求中获取数据返回

JS(放入static / hello.html通过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>

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"}}

答案 4 :(得分:12)

您可以使用XMLHttpRequest,提取API,...

如果要使用XMLHttpRequest,可以执行以下

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);
};

或者如果您想使用提取API

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);
    });

答案 5 :(得分:6)

您是否知道JavaScript具有内置的方法和库来创建表单并提交它们?

我在这里看到很多答复,都要求使用3rd party库,我认为这太过分了。

我将使用纯Javascript执行以下操作:

/* webpackMode: "lazy", webpackChunkName: "[request]", webpackPreload: true */

通过这种方式(A),您不需要依靠第三方来完成这项工作。 (B)全部内置于所有浏览器中,(C)速度更快,(D)有效,请随时尝试。

我希望这会有所帮助。 高

答案 6 :(得分:5)

有一种简单的方法可以包装数据并将其发送到服务器,就像使用POST发送HTML表单一样。 您可以使用FormData对象执行以下操作:

data = new FormData()
data.set('Foo',1)
data.set('Bar','boo')

let request = new XMLHttpRequest();
request.open("POST", 'some_url/', true);
request.send(data)

现在,您可以像处理常规HTML表单一样,在服务器端处理数据。

其他信息

建议您在发送FormData时不要设置Content-Type标头,因为浏览器会处理它。

答案 7 :(得分:2)

navigator.sendBeacon()

如果您只需要POST数据并且不需要服务器响应,则最短的解决方案是使用navigator.sendBeacon()

const data = JSON.stringify({
  example_1: 123,
  example_2: 'Hello, world!',
});

navigator.sendBeacon('example.php', data);

答案 8 :(得分:2)

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
 '           Content-Type': 'application/json',
           },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => {
      console.log('Success:', data);
     })
 .catch((error) => {
         console.error('Error:', error);
   });

答案 9 :(得分:1)

这里最流行的答案没有展示如何从 POST 取回数据。此外,当将数据发送到最新版本的 NodeJS 时,流行的“获取”解决方案在最新版本的 Chrome 中不起作用,除非您传递标头并解开 response.json() 承诺。此外,流行的答案不使用 async/await。

这是我能想到的最干净、最完整的解决方案。

async function postJsonData(jsonObject) {
    const response = await fetch("/echo", {
        method: "POST",
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(jsonObject)
    });
    
    const actualResponse = await response.json();
}

答案 10 :(得分:1)

这是您(或其他任何人)可以在他们的代码中使用的一个很好的函数:

function post(url, data) {
    return new Promise((res, rej) => {
        let stringified = "";
        for (const [key, value] of Object.entries(data))
            stringified += `${stringified != '' ? '&' : ''}${key}=${value}`

        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4)
                if (xhr.status == 200)
                    res(xhr.responseText)
                else
                    rej({ code: xhr.status, text: xhr.responseText })
        }
        xhr.open("POST", url, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        xhr.send(stringified);
    })
}

答案 11 :(得分:0)

您也可以使用:https://github.com/floscodes/JS/blob/master/Requests.js

您可以轻松发送 http 请求。只需使用:

HttpRequest("https://example.com", method="post", data="yourkey=yourdata");

就是这样!如果站点受 CSRF 保护,它甚至应该可以工作。

或者只是使用发送一个 GET-Request

HttpRequest("https://example.com", method="get");
相关问题