JavaScript:将数据发送到Web服务器

2025-12-17 06:37:12

发送数据:基础

向服务器发送数据通常是通过 HTTP 的 post 方法完成的。在这种情况下,请求正文包含要发发送的数据。数据格式取决于服务器的期望。它可以是:

键值对,例如直接提交表单时。Json 格式:可以用于更多结构化数据。

将表单数据发送到服务器

如果 Web 服务器需要直接的表单数据,您可以使用 JavaScript 的 FormData 对象来封装要发送的信息。下面是一个示例的表单,用于选择最强壮的动物以及处理表单提交的JS代码。

Which one is the strongest?




:

// Handle form submission

document.querySelector("form").addEventListener("submit", e => {

// Cancel default behavior of sending a synchronous POST request

e.preventDefault();

// Create a FormData object, passing the form as a parameter

const formData = new FormData(e.target);

// Send form data to the server with an asynchronous POST request

fetch("https://thejsway-server.herokuapp.com/animals", {

method: "POST",

body: formData

})

.then(response => response.text())

.then(result => {

document.getElementById("result").textContent = result;

})

.catch(err => {

console.error(err.message);

});

});

页面显示:

事件监听器首先禁用默认的表单提交行为,即向 POST 服务器发送同步 HTTP 请求。相反,FormData 对象是用表单本身(e.target表达式)作为参数来创建的。所有表单字段都会自动添加为该对象中的键值对。

一旦表单字段封装在 FormData 对象中,就会使用前面看到的 fetch() 方法向https://thejswayserver发送异步请求。fetch() 调用的第二个参数将HTTP方法设置为 POST 并将表单数据添加到请求的正文中。

最后,当服务器响应异步请求时,页面的 result 元素会更新。

该FormData 对象也可以独立于任何形式使用,将自定义键值对发送到服务器。这是一个非常基本的表单示例,仅包含一个按钮。

当用户点击按钮时,自定义数据被添加到 FromData 对象中,并通过异步 POST请求发送到服务器。

document.getElementById("buyButton").addEventListener("click", () => {

// Create a new, empty FormData object

const formData = new FormData();

// Fill the object with key/value pairs

formData.append("size", "L");

formData.append("color", "blue");

// Send data to the server

fetch("https://thejsway-server.herokuapp.com/tshirt", {

method: "POST",

body: formData

})

.then(response => response.text())

.then(result => {

document.getElementById("result").textContent = result;

})

.catch(err => {

console.error(err.message);

});

});

将Json数据发送到服务器

// Create an array containing two objects

const cars = [

{

model: "Peugeot",

color: "blue",

registration: 2012,

checkups: [2015, 2017]

},

{

model: "Citroën",

color: "white",

registration: 1999,

checkups: [2003, 2005, 2007, 2009, 2011, 2013]

}

];

// Send this array as JSON data to the server

fetch("https://thejsway-server.herokuapp.com/api/cars", {

method: "POST",

headers: {

Accept: "application/json",

"Content-Type": "application/json"

},

body: JSON.stringify(cars)

})

.then(response => response.text())

.then(result => {

console.log(result);

})

.catch(err => {

console.error(err.message);

});

输出结果:

fetch() 调用的第二个参数设置为要使用的HTTP方法 POST,更新请求标头以指示数据格式为JSON,并将JavaScript 数据的 JSON表示添加到请求体中。