原生ajax发送POST请求到controller的代码
时间: 2024-05-29 11:10:47 浏览: 14
var xhr = new XMLHttpRequest();
xhr.open('POST', '/controller/url', true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// 请求成功后的处理
console.log(xhr.responseText);
} else {
// 请求失败后的处理
console.log(xhr.status);
}
};
var data = {
// POST请求的数据
};
xhr.send(JSON.stringify(data));
相关问题
原生ajax发送请求到controller的代码
以下是一个原生Ajax发送请求到Controller的示例代码:
```javascript
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// 处理响应数据
console.log(xhr.responseText);
} else {
// 处理错误
console.error('请求出错了');
}
}
};
xhr.open('GET', '/controller/api');
xhr.send();
}
```
这段代码使用了`XMLHttpRequest`对象来发送GET请求到`/controller/api`地址,并在请求完成后处理响应数据。其中,`onreadystatechange`属性指定了响应状态改变时的回调函数,`readyState`属性表示当前请求状态,`status`属性表示响应状态码,`responseText`属性表示响应文本。在处理响应时,我们可以根据响应状态码和响应文本来进行相应的处理。
原生ajax发送post请求
可以使用以下代码发送原生Ajax Post请求:
```javascript
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
var data = JSON.stringify({
"key": "value"
});
xhr.send(data);
```
其中,url是请求的地址,data是请求的数据,需要使用JSON.stringify转换为字符串。在send方法中传入data即可发送Post请求。在设置请求头时,需要指定Content-Type为application/json;charset=UTF-8。当xhr的状态为4且状态码为200时,表示请求成功,可以处理返回的数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)