form表单get和post提交方式的不同

在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的语法更简洁,但是不是所有旧版浏览器都支持。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值