如何写一个用ajax向/useradd传输name,id等参数并添加传输成功提示的语句
时间: 2024-03-17 14:40:17 浏览: 12
您可以按照以下步骤编写一个使用 Ajax 发送 HTTP POST 请求到 /useradd 的代码段:
1. 创建 XMLHttpRequest 对象
```
var xhr = new XMLHttpRequest();
```
2. 设置请求方式和请求地址
```
xhr.open("POST", "/useradd", true);
```
3. 设置请求头信息
```
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
```
4. 设置回调函数,处理服务器响应
```
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// 处理服务器响应
console.log(xhr.responseText);
alert("传输成功!");
}
};
```
5. 发送请求并传递参数
```
xhr.send("name=" + name + "&id=" + id);
```
完整代码:
```
var xhr = new XMLHttpRequest();
xhr.open("POST", "/useradd", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
alert("传输成功!");
}
};
xhr.send("name=" + name + "&id=" + id);
```