JavaScript POST
本教程讲授如何在不使用 JavaScript 表单的情况下发送 POST
数据。
在 JavaScript 中使用 XHR(XML HTTP Request)
发送没有表单的 POST
数据
XHR
是一个对象,用于在 JavaScript 中发出 HTTP
请求。它有助于与服务器进行交互并在客户端和服务器之间交换数据。即使不刷新整个页面,我们也可以从服务器中提取数据。它使用户仅破坏页面的一部分就可以继续工作。我们可以使用这种方法发送 POST 数据,而无需使用表单。
const URL = 'delftstack.com'
var xhr = new XMLHttpRequest();
xhr.open('POST', URL, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({name: 'DelftStack'}));
在 JavaScript 中使用 Fetch
API 发送没有表单的 POST
数据
JavaScript 提取 API,例如 XHR
,有助于将 HTTP
请求发送到服务器。但是 XHR
没有利用承诺,导致代码混乱不整洁。要使用 Fetch API,我们必须调用 fetch()
方法。它接受以下参数:
URL
:从中请求数据的 API 的 URL。object
:这是一个对象,用于指定有关所请求类型的其他属性。它具有 3 个属性:method
:它指定诸如GET
,POST
之类的方法。在这种情况下,其值应为POST
,因为我们正在发出POST
请求。body
:body
对象包含要发送的数据。headers
:这是一个可选参数,可帮助我们对HTTP
请求和响应标头执行各种操作。
在 fetch()
方法之后,我们指定诺言方法 then()
和 catch()
。如果 fetch()
返回的 promise
是 resolved
,则执行 then()
中指定的函数,否则返回的 promise
是 rejected
,并调用 catch()
内部的函数。
let data = {name: 'DelftStack'};
fetch('https://randomuser.me/api/?results=10', {
method: 'POST',
body: JSON.stringify(data)
}).then(res => {
console.log('Promise resolved', res);
});
在 JavaScript 中使用 Navigator.sendBeacon()
发送没有表单的 POST
数据
Navigator.sendBeacon()
方法有助于通过 HTTP 请求将数据异步发送到 Web 服务器。它的主要应用是将网站分析数据发送到服务器,但也可以用于发送 POST
数据。
let data = {name: 'DelftStack'};
navigator.sendBeacon('https://randomuser.me/api/?results=10', data);
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。