使用Javascript/form提交GET/POST数据提交方式
时间: 2024-10-17 14:09:05 浏览: 40
在JavaScript中,你可以使用`XMLHttpRequest`对象或者现代浏览器提供的`fetch()`函数来通过GET或POST方法提交表单数据。以下是两种常见的方法:
1. **使用XMLHttpRequest (GET)**:
```javascript
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your-url?param1=value1¶m2=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的语法更简洁,但是不是所有旧版浏览器都支持。
阅读全文
相关推荐


















