Last active
September 21, 2016 04:27
-
-
Save Yhzhtk/6302455 to your computer and use it in GitHub Desktop.
原生Ajax用法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 所有现代浏览器 (IE7+、Firefox、Chrome、Safari 以及 Opera) 都内建了 XMLHttpRequest 对象。 | |
var xmlhttp = new XMLHttpRequest(); | |
// onreadystatechange 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 | |
xmlhttp.onreadystatechange = function() { | |
//存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。 | |
//0: 请求未初始化 | |
//1: 服务器连接已建立 | |
//2: 请求已接收 | |
//3: 请求处理中 | |
//4: 请求已完成,且响应已就绪 | |
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { | |
// responseXML 获取xml的响应 responseText获取字符串的响应 | |
doRes(xmlhttp.responseText); // 处理返回的数据 | |
} | |
}; | |
var url = "./ajax?act=new"; | |
//open方法 method:请求的类型;GET 或 POST; url:文件在服务器上的位置; async:true(异步)或 false(同步) | |
// get | |
xmlhttp.open("GET", url, true); | |
xmlhttp.send(); | |
// post | |
xmlhttp.open("POST",url,true); | |
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 设置http头 | |
xmlhttp.send("fname=Bill&lname=Gates"); // 发送post参数 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
注意,ajax不支持跨域。如果要跨域,可以使用jsonp(需要目的服务器支持)或者自己服务器中转的方式实现。