纯粹的 AJAX

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function saveInfo() {
var XHR = null;
var FD = new FormData();
var name = document.getElementById("name").value;

if (window.XMLHttpRequest)
XHR = new XMLHttpRequest();
else if (window.ActiveXObject)
XHR = new ActiveXObject("Microsoft.XMLHTTP");

FD.append("name", name);

XHR.onreadystatechange = function ()
{
if (XHR.readyState == 4 && XHR.status == 200)
{
var text = XHR.responseText; // 返回的文本
}
}

XHR.open('POST', 'index.php', true)
XHR.send(FD);
}

以云笺保存信息的函数为例:

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function saveInfo() {
var XHR;
var FD = new FormData();
var name = document.getElementById("name").value;
var info = document.getElementById("info").value;

if (name == "") return ;
// 去掉首尾空格
var noblank_name = name.replace(/(^\s*)|(\s*$)/g,"");
if (noblank_name != name){
name = noblank_name;
document.getElementById("name").value = name;
}

XHR = null;

if (window.XMLHttpRequest)
{
XHR = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}

FD.append("name", name);
FD.append("info", info);

XHR.onreadystatechange = function ()
{
if (XHR.readyState == 4 && XHR.status == 200)
{
mdui.snackbar({
message: '保存成功',
buttonText: '历史',
onButtonClick: function() {
window.open("index.php?h=1&n=" + encodeURI(name));
},
});

save_time = (new Date()).getTime();
save_text = info;
}
}

XHR.open('POST', 'index.php', true);

XHR.send(FD);

document.getElementById('info').focus();

return false;
}

jQuery用法

1
2
3
4
5
6
7
8
9
10
11
// 实时聊天获取头像例子
function get_head(fromid, toid) {
$.post(
API_URL+"getHead", // 网址
{"fromid":fromid, "toid":toid}, // 数据
function(e) { // 返回后
from_head = e.from_head;
to_head = e.to_head;
}, "json" // 格式是 json
);
}