在前端JavaScript中,我们会利用Ajax技术来实现客户端与服务端的异步传输。在本文中,我使用原生的javascript语句,编辑了自己的Ajax库,以便于后面自己的使用。
1.Ajax库代码(JS文件)
ajax函数中需要两个参数。
一个是http请求的方法(method:GET/POST),二者的区别,有兴趣可以自行了解;另一个是httpq请求的文件地址(url),在该项目中请求的是本地的文档。
JSON解析器的使用:
var arr = JSON.parse(oAjax.responseText);** //使用JSON解析器更加高效
function ajax(method, url) {
var type = url.substr(url.length - 4, 4); //文档后缀-文档类型
var arr = null;
var oAjax = new XMLHttpRequest(); //XMLHttpRequest()只有responseText和responseXML属性?
oAjax.open(method, url + '?time=' + new Date().getTime(), true);
oAjax.send();
oAjax.onreadystatechange = function() {
//判断ajax的状态码//
if (oAjax.readyState == 4) {
if (oAjax.status == 200) {
//alert(typeof(oAjax.responseText));
alert(oAjax.responseText);
//判断文档类型是否为json
if (type == "json") {
//arr = eval(oAjax.responseText);
arr = JSON.parse(oAjax.responseText); //使用JSON解析器更加高效安全
alert(arr[2].name);
} else {}
} else {
//alert("failed to page request,error code:"+oAjax.status);
}
} else {
//alert("failed to send httprequest,error code:"+oAjax.readyState);
}
}
}
2.HTML文件
文档中只定义了一个按钮,点击按钮,会弹窗提示http响应的结果,本次演示的结果是JSON文件。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AJAX</title>
<script src="../js/myAjax.js"></script>
<script>
window.onload = function(){
var oBtn = document.getElementById('btn1');
oBtn.onclick = function(){
//ajax('GET','../a.txt');
ajax('GET','../json/user.json');
}
}
</script>
</head>
<body>
<input id="btn1" type="button" value="read"/>
</body>
</html>
3.JSON文件
JSON文件可以根据固定的规则和自己的需要,进行编写。
JSON 取值规则:数字-(整数或浮点数)/ 字符串-(在双引号中)/ 逻辑值-(true 或 false)/ 数组-(在方括号中)/ 对象-(在花括号中)/ null
[{"user":"dalo", "password":"1234567"},
{"user":"as", "password":"567456"},
{"name":"Bill Gates",
"street":"Fifth Avenue New York 666",
"age":56,
"phone":"555 1234567"}]