fetch 使用 form data 方式提交

本文介绍如何使用JavaScript的fetch API发送POST请求,并设置了正确的Content-Type为application/x-www-form-urlencoded。文章详细解释了如何将对象转换成URL编码字符串并作为请求体发送。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import queryString from 'query-string';

fetch 参数如下,
1.需要设置content-type application/x-www-form-urlencoded
2.body 进行param 转化为a=1&b=2 的形式
则提交到服务端的内容与post内容相同

  headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            }, 
            method: "POST",
            body: queryString.stringify(data)

参考文档https://stackoverflow.com/questions/29775797/fetch-post-json-data

在JavaScript中,你可以使用`XMLHttpRequest`对象或者现代浏览器提供的`fetch()`函数来通过GET或POST方法提交表单数据。以下是两种常见的方法: 1. **使用XMLHttpRequest (GET)**: ```javascript var xhr = new XMLHttpRequest(); xhr.open('GET', 'your-url?param1=value1&param2=value2'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; ``` 在这个例子中,GET请求将包含查询字符串的形式发送。 2. **使用XMLHttpRequest (POST)**: ```javascript var xhr = new XMLHttpRequest(); xhr.open('POST', 'your-api-url'); xhr.setRequestHeader('Content-Type', 'application/json'); // 或者 'application/x-www-form-urlencoded' 如果数据是键值对形式 // JSON 数据 var data = { key1: 'value1', key2: 'value2' }; xhr.send(JSON.stringify(data)); xhr.onreadystatechange = function() { if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) { console.log(xhr.responseText); } }; ``` 对于POST方法,你需要设置正确的Content-Type,并且通常会发送JSON格式的数据,而不是直接在URL中显示。 3. **使用fetch (GET or POST)**: ```javascript fetch('your-url', { method: 'GET', // 或者 'POST', headers: { 'Content-Type': 'application/json' // 或者 'application/x-www-form-urlencoded' }, body: JSON.stringify({ your_data_here }) // 只有在POST时需要 }) .then(response => response.text()) .then(data => console.log(data)) .catch(error => console.error(error)); ``` fetch API的语法更简洁,但是不是所有旧版浏览器都支持。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值