增城建设局网站,长沙高新区住房和建设管理局网站,小公司网站建设费用,最新舆情信息网ajax的优点
可以无需刷新页面而与服务器进行通信允许你根据用户事件来更新部分页面内容
ajax的缺点
没有浏览历史#xff0c;不能回退存在跨域问题SEO不友好 get请求 button点击发送请求/buttondiv idresult/divscript不能回退存在跨域问题SEO不友好 get请求 button点击发送请求/buttondiv idresult/divscriptconst btn document.getElementsByTagName(button)[0];const result document.getElementById(result);btn.onclick function() {//创建对象const xhr new XMLHttpRequest();//超时设置2s设置xhr.timeout 2000;//超时回调xhr.ontimeoutfunction(){alert(网络异常请稍后重试);}//网络异常回调xhr.onerrorfunction(){alert(你的网络似乎出了一点问题);}//设置响应体数据的类型//xhr.responseType json;//初始化 设置请求方法和urlxhr.open(GET, http://127.0.0.1:8000/server);//请求参数xhr.open(GET, http://127.0.0.1:8000/server?a100b200);//设置请求头xhr.setRequestHeader(Content-Type,application/x-www-form-urlencoded);//发送xhr.send();//事件绑定 处理服务器返回的结果//readystate是xhr对象中的属性表示状态 0 1 2 3 4//0表示未初始化 1表示open方法调用完毕 2表示send方法调用完毕//3表示服务端返回部分结果 4表示服务端返回所有结果xhr.onreadystatechange function() {//判断服务端返回了所有的结果if (xhr.readyState 4) {//判断响应状态码 200 404 500//2xx 2开头都代表成功if (xhr.status 200 xhr.status 300) {console.log(xhr.status); //状态码console.log(xhr.statusText); //状态字符串console.log(xhr.getAllResponseHeaders); //所有响应头console.log(xhr.response); //响应体result.innerHTML xhr.response;}}}}
/scriptpost请求和get请求差不多 post通过send()设置请求体比如send(‘a100b200’)
abort()方法可以手动取消ajax请求