第六章 jQuery与ajax的应用
1 load()方法
1)载入HTML方法
load(url [,data] [,callback]);
$(function(
$("#send").click(function(){
$(“resText”).load(“test.html”);
});
));
只加载test.html中class为para的内容
$(“resText”).load(“test.html .para”);
- 传递方式
3)回调参数
$("#resText").load(“test.html”,function(responseText,textStatus,XMLHttpRequest){
//responseText;请求返回的内容
//textStatus 请求的状态:success,error,notmodified,timeout
//XMLHttpRequest 对象
});
2
.
g
e
t
(
)
方
法
与
.get()方法与
.get()方法与.post()方法
1)$.get(url [,data] [,callback] [,type])
例子:
KaTeX parse error: Expected '}', got 'EOF' at end of input: …hp", {username:("#username").val(),
password:$(“password”).val()},
function(data,textStatus){
alert(111);
},
“json”);
2)post方法与get方法类似
3
.
g
e
t
S
c
r
i
p
t
(
)
方
法
与
.getScript()方法与
.getScript()方法与.getjson()方法
1)$.getScript(‘test.js’,function(){
alert();
});
2) $.getScript(‘test.json’,function(data){
//data 返回的数据
$.each(data,function(commentIndex,comment){
});
});
4 $.ajax()方法
$.ajax(options)
$.getScript()等价写法
$(function(){
$(’#send’).click(function(){
$.ajax({
type:“GET”,
url:“test.js”.
dataType:“script”
});
});
});
$.getJson()等价写法
$(function(){
$.ajax(function(){
type:“GET”,
url:“test.json”,
dataType:“json”,
success:function(data){
$(‘resText’).empty();
}
});
});
5 序列化元素
1)serialize();
2)serializeArray()方法,将dom元素序列化后,返回json格式的数据
(
"
:
c
h
e
c
k
b
o
x
,
:
r
a
d
i
o
"
)
.
s
e
r
i
a
l
i
z
e
A
r
r
a
y
(
)
;
3
)
(":checkbox,:radio").serializeArray(); 3)
(":checkbox,:radio").serializeArray();3).param();
var obj = {a:1,b:2,c:3};
var k = $.param(obj);
alert(k);//输出a=1&b=2&c=3
6 ajax全局事件
附录:
1 解析xml
success:function(xml){
$(xml).find(“student”).each(
var id =
(
t
h
i
s
)
.
c
h
i
l
d
r
e
n
(
"
i
d
"
)
;
v
a
r
i
d
v
a
l
u
e
=
i
d
.
t
e
x
t
(
)
;
a
l
e
r
t
(
i
d
v
a
l
u
e
)
;
a
l
e
r
t
(
(this).children("id"); var id_value=id.text(); alert(id_value); alert(
(this).children("id");varidvalue=id.text();alert(idvalue);alert((this).attr(“email”));
);
}
2 禁用缓存(项目中问题:数据已经更新,但传递的还是旧数据,解决方案:禁用缓存)
post方法 默认禁用缓存
get方法
$.get(‘ajax.xml?’+(+new Date),function(xml){…})//(+new Date)等价于new Date.get();