Ajax Asynchronous JavaScript and XML 异步的JavaScript和XML
ajax通过与后台服务器进行少量的数据交换,ajax可以使页面实现异步更新,即不需要重新加载整个页面
1.创建XMLHttpRequest对象
所有现代浏览器
var xhr = new XMLhttpRequest();
老版本的 ie
var xhr = new ActiveXObect("Micrsoft.XMLHTTP");
2.向服务器发送请求
xhr.open(method,url,async) ???//method 可选 GET / POST ?????????????????????????//url ?文件在服务器上的位置 ?????????????????????????//async true(异步),false(同步)
xhr.send(string) ???//仅适用于POST请求 ???将请求发送到服务器
GET与POST优缺点
与POST相比GET更简单,更快,并且大部分情况都能用然而 ???以下情况中要用POST请求 ???·无法使用缓存文件(更新服务器上的文件或数据库) ???·向服务器发送大量数据(POST没有数据量限制) ???·发送包含位置字符的用于输入时 POST 比GET跟稳定
简单的GET请求 ajax是在服务器端的请求 所以本地模拟一个
我使用的是gitbash 切换到本地对应目录
$ npm install --global http-server //node包管理工具下载
$ http-server //运行http-server
服务器挂起了
html
?<span>你好</span> ?<button onclick="lodMessage()">change</button>
js
?????var lodMessage = () => { ???????console.log(‘发送请求‘); ???????var xhr = new XMLHttpRequest(); ???????console.log(xhr.readyState); ???????xhr.onreadystatechange = function () { ?????????console.log(xhr.readyState); ?????????console.log(xhr.status); ?????????if (xhr.readyState == 4 && xhr.status == 200) { ???????????document.getElementsByTagName(‘span‘)[0].innerHTML = xhr.responseText; ?????????} ?????????????????} ???????xhr.open(‘GET‘, ‘http://127.0.0.1:8080/demo.php‘, true); ???????xhr.send(); ?????}
demo.php
<?php ?echo ‘changed‘;
?>
这样打开本地的 localhost:8080/01-get.html 即可 点击按钮 就可以显示在 demo.php里面请求回来的数据
点击前
点击后
当我改变demo.php里的内容
<?php ?echo ‘changedededededed‘;?>
再次刷新页面后再次点击 button 发送请求 期望得到改变后的demo.php的值
然而并没有的到更新后的数据 (这种情况 不是每次都会碰到 , 但是的确碰到了)
这是因为 两次请求,浏览器将数据缓存下来了
解决办法 (让请求不一样)
改变 xhr.open 给url加一个唯一的id
这样 浏览器就不会使用缓存的数据
GET时传一些数据
POST请求
更换open方法的method
xhr.open(‘POST‘,‘http://127.0.0.1:8080/demo.php‘,true)
添加请求头规定想要发送的数据类型
xhr.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘)
http的content-type还有好多种 http://tool.oschina.net/commons
send方法中添加数据
xhr.send(‘name=weibin&age=12‘);
xhr.status与xhr.readyState的值以及其意义
//xhr.status200-300 ???????访问成功304 ???????????????请求没有改变浏览器已经缓存下来了404 ???????????????文件不存在500 ???????????????服务器故障502 ???????????????错误的访问503 ???????????????服务器不可用
//xhr.readyState0 ???请求未初始化1 ???服务器链接简历2 ???发送send请求3 ???内容下载4 ???完成
ajax 默认是不能请求跨域的资源的
请求跨域资源的两种方法 1.jsonp 2.使用 jquery封装的ajax
Ajax深入理解
原文地址:https://www.cnblogs.com/96weibin/p/8709483.html