1.封装ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*1创建xhr对象*/
function createXhr() {
var xhr = null;
if (XMLHttpRequest) {
xhr = new XMLHttpRequest();
}else{
//兼容IE6以前的老IE
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
}
function ajax(info) {
var xhr=createXhr();
var type,async;
type=info.type=="post"?"post":"get";
async=info.async=="true"?"true":"false";
xhr.open(type,info.url,async);
if (type == "post") {
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
}
xhr.onreadystatechange=function () {
if(xhr.readyState==4){
if(xhr.status==200){
info.success(xhr.responseText)
}else{
info.error();
}
}
}
xhr.send(info.data);
}

2.使用ajax

1
2
3
4
5
6
7
8
9
10
11
12
13
btn.onclick=function () {
ajax({
type:'get',
url:'php/01-gettime.php',
async:'true',
success:function (a) {
time.innerHTML=a;
},
error:function () {
alert('错误')
}
})
}

使用jquery ajax()

1
2
3
4
5
6
7
8
9
10
11
12
$("#btn").click(function () {
$.ajax({
url:"php/04-hw.php",
dataType:"text",
type:'get',
success:function (data) {
alert(data);
},
error:function () {
alert('error')
}
})
  • dataType参数
    • xml”: 返回 XML 文档,可用 jQuery 处理。
    • “html”: 返回纯文本 HTML 信息;包含的 script 标签会在插入 dom 时执行。
    • “script”: 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 “cache” 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)
    • “json”: 返回 JSON 数据 。
    • “jsonp”: JSONP 格式。使用 JSONP 形式调用函数时,如 “myurl?callback=?” jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。
    • text”: 返回纯文本字符串