1、jQuery 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
|
<!DOCTYPE html>
<html>
<head>
<title>
JQuery ajax应用
</title>
<script src=
"http://libs.baidu.com/jquery/1.10.2/jquery.min.js"
></script>
<script>
$(
function
(){
$(
"#btn1"
).click(
function
(){
// 点击事件里面发送一个ajax请求
$.ajax({
url :
"demo_test.txt"
,
//请求地址
success :
function
(result){
$(
"#p1"
).html(result);
//成功回调函数
}
});
});
});
</script>
</head>
<body>
<p id=
"p1"
>jQuery ajx应用</p>
<input type=
"button"
id=
"btn1"
value=
"点一下"
>
</body>
</html>
|
点击按钮,将p中的文件内容修改,通过ajax请求.
2、ajax函数解析
语法:
$.ajax({
name : value,
name : value,
name : value,
...
});
其中,参数如下图
3、实例解析
1)指定响应数据类型dataType
1
2
3
4
5
6
|
$(
"#btn2"
).click(
function
(){
$.ajax({
url :
"demo_ajax_script.js"
,
dataType :
"script"
});
});
|
2)各中状态下的回调函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
$(
"#btn3"
).click(
function
(){
$.ajax({
url :
""
,
beforeSend :
function
(){
$(
"#div1"
).css({
"background-color"
:
"red"
,
"width"
:
"80px"
,
"height"
:
"80"
});
console.log(
"beforeSend"
);
},
complete :
function
(){
$(
"#div1"
).css({
"background-color"
:
"green"
,
"width"
:
"80px"
,
"height"
:
"80"
});
console.log(
"complete"
);
},
error :
function
(){
$(
"#div1"
).css({
"background-color"
:
"black"
,
"width"
:
"40px"
,
"height"
:
"40"
});
console.log(
"error"
);
}
});
});
|
得到console中的返回值
由此可以看出ajax调用的顺序
beforeSend --> success/error --> complete
无论成功与否,最终都会调用complete回调方法,相当于java中的finally
4、ajaxSetup()方法
用于设置ajax的参数
1
2
3
4
5
6
7
8
9
10
|
$(
"#btn1"
).click(
function
(){
// 点击事件里面发送一个ajax请求
$.ajaxSetup({
url :
"demo_test.txt"
,
//请求地址
success :
function
(result){
$(
"#p1"
).html(result);
//成功回调函数
}
});
$.ajax();
});
|
5、get()方法
发送一个get请求到指定url地址
参数
语法:$.get(URL,data,function(data,status,xhr),dataType)
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
|
<!DOCTYPE html>
<html>
<head>
<title>
JQuery ajax应用
</title>
<script src=
"http://libs.baidu.com/jquery/1.10.2/jquery.min.js"
></script>
<script>
$(
function
(){
$(
"#btn1"
).click(
function
(){
$.get(
"/try/ajax/gethint.php?q="
+$(
"#txt1"
).val(),
//url
function
(data , status){
$(
"p"
).html(data);
}
//回调方法
);
});
});
</script>
</head>
<body>
<p>ajax 的Get和POST方法</p>
<input type=
"text"
id=
"txt1"
><br>
<input type=
"button"
id=
"btn1"
value=
"点一下"
>
<p></p>
</body>
</html>
|
$.post()方法
事例
1
2
3
4
5
6
7
8
|
//post方法
$.post(
"demo_ajax_gethint.php"
,
//url
{suggest : $(
"#txt1"
).val()},
//参数
function
(data, status){
$(
"p:eq(1)"
).html(data);
}
//回调函数
);
|
get()和post()方法均可以用ajax()代替
1
2
3
4
5
6
7
8
|
$.ajax({
type:
"POST"
,
url :
"demo_ajax_gethint.php"
,
data :
"suggest="
+ $(
"#txt1"
).val(),
success :
function
(data){
$(
"p:eq(1)"
).html(data);
}
});
|