js代码中httpRequest介绍
时间: 2024-03-01 10:56:20 浏览: 26
httpRequest是一个封装了XMLHttpRequest对象的JavaScript函数,用于在Web应用程序中向服务器发送HTTP请求并获取响应。使用httpRequest可以实现异步数据交换和局部页面刷新,从而提高Web应用程序的性能和用户体验。
httpRequest包括以下几个步骤:
1. 创建XMLHttpRequest对象
2. 设置请求的方法、URL和是否异步
3. 发送请求
4. 监听XMLHttpRequest对象的状态变化和响应数据的到达
5. 处理响应数据
下面是一个简单的httpRequest示例:
```
function httpRequest(method, url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
callback(xhr.responseText);
}
};
xhr.open(method, url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.send(data);
}
httpRequest("POST", "/api/login", JSON.stringify({username: "test", password: "123456"}), function(response) {
console.log(response);
});
```
这个示例中,httpRequest函数接受四个参数:请求方法、请求URL、请求数据和响应回调函数。在函数内部,首先创建了一个XMLHttpRequest对象,然后设置了onreadystatechange事件处理函数,当XMLHttpRequest对象的状态变化时会触发该函数。在发送请求前设置了请求头,使用send方法发送请求,并将请求数据以JSON字符串的形式发送。最后,在响应回调函数中处理响应数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
<script type="text/javascript"> var httpRequest = new XMLHttpRequest(); httpRequest.open('GET','http://1.14.137.211:8888/tealist',true); httpRequest.send(); httpRequest.onreadystatechange = function(){ if(httpRequest.readyState == 4 && httpRequest.status ==200 ){ var data = httpRequest.responseText; var data = JSON.parse(data); console.log(data); function test1(){ $(".increment").onclick = function(){ let n = $(this).siblings(".itxt").val(); console.log(n); n++; $(this).siblings(".itxt").val(n); } return; } function test2(){ $(".decrement").onclick = function(){ let n = $(this).siblings(".itxt").val(); console.log(n); if (n == 0) { return false; } n--; $(this).siblings(".itxt").val(n); } return; } data.forEach(element => { let html = ${element.name}${element.price}¥ - <input type="text" class="itxt" value="0"> + $("#pics").append(html); //document.querySelector("#pics").innerHTML = html; }); } } </script>
![](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)