网页如何发送post请求
时间: 2023-07-18 11:20:57 浏览: 47
网页发送 POST 请求的方式可以通过表单提交(form submit)或 Ajax 请求(XMLHttpRequest)实现。
1. 表单提交方式
在 HTML 中使用 form 标签,设置 method 属性为 POST,action 属性为请求的 URL 地址。在 form 标签内定义 input 标签,设置 name 属性和 value 属性,以便将数据传递给后端。最后通过调用 submit() 方法提交表单。
示例代码:
```html
<form method="POST" action="/submit">
<label for="username">Username:</label>
<input type="text" id="username" name="username"><br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
```
2. Ajax 请求方式
使用 JavaScript 发送 Ajax POST 请求,可以使用 XMLHttpRequest 对象。首先创建 XMLHttpRequest 对象,然后使用 open() 方法设置请求方式和请求 URL,接着设置请求头信息,最后发送请求并处理响应。
示例代码:
```javascript
const xhr = new XMLHttpRequest();
xhr.open('POST', '/submit', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
const data = { username: 'test', password: '123456' };
xhr.send(JSON.stringify(data));
```
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)