今天继续ajax的学习
试过了最简单的Javascript的写法之后,尝试一下比较方便的jQuery方法。
$.load()方法
.load()方法是局部方法,因为它需要一个包含元素的jQuery对象作为前缀,而$.get()和$.post()是全局方法,无需指定某个元素,对于用途而言,.load()适合做静态文件的异步获取,而对于需要传递参数到服务器页面的,$.get()和$.post()更加合适。
$(function(){
$("input").click(function(){
$.get('test.php?url=baidu.com',function(response,status,xhr){
$('#box').html(response);
})
})
});
$.post()
POST提交不是能使用url传参。post提交可以使用字符串形式传参,自动转换为http消息实体传参
$(function () {
$("input").click(function () {
$.post('test.php','url=baidu.com', function (response,status,xhr) {
$('#box').html(response);
})
})
}); //post提交可以使用对象键值对
$(function () {
$("input").click(function () {
$.post('test.php',{
url:'baidu.com'//post提交可以使用对象键值对
}, function (response,status,xhr) {
$('#box').html(response);
})
})
});
$.get()方法
$.get()方法有四个参数,前面三个参数和.load()一样,多了一个第四参数type,即服务器返回的内容格式,包括xml,json,script,html,text等,第一个参数为必选参数,后面三个为可选参数
$.ajax()方法
$.ajax()是所有AJAX方法中最底层的方法,所有其他方法都是基于$.ajax()方法的封装,这个方法只有一个参数,传递一个各个功能键值对的对象。
$.ajax()方法对象参数列表
参数 | 类型 | 说明 |
---|---|---|
url | string | 发送请求的地址 |
type | string | 请求方法,默认GET |
timeout | Number | 设置请求超时的时间 |
data | Object或String | 发送到服务器的对象,键值对字符串或对象 |
datatype | String | 返回的数据类型,比如html,XML,json等 |
success | Function | 请求成功后调用的回调函数 |
complete | Function | 请求完成后调用的回调函数 |
error | Function | 请求失败后调用的回调函数 |
$(function () {
$("input").click(function () {
$.ajax({
type : "POST",
url: 'test.php',
data:{
url: 'baidu.com'
},
success : function(response,status,xhr){
$('#box').html(response);
}
})
})
});
表单序列化
Ajax用的最多的地方莫过于表单操作,而非传统的表单操作是通过submit提交将数据传输到服务器,如果使用Ajax异步处理的话,我们需要将每一个表单元素获取才能提交,这样工作效率就打打降低。
<body>
<form action="">
用户名: <input type="text" name="user" />
邮件: <input type="text" name="email" />
<input type="button" value="提交"/>
</form>
<div id="box"></div>
<script type="text/javascript">
$(function () {
$("form input[type=button]").click(function () {
$.ajax({
type: 'POST',
url: 'test.php',
data: {
user: $('form input[name=user]').val(),
email: $("form input[name=email]").val(),
},
success: function(response){
$("#box").html(response);
}
})
})
});
</script>
</body>
serialize()方法不但可以序列化表单内的元素,还可以直接获取单选框,复选框和下拉列表框等内容
<body>
<form action="">
用户名: <input type="text" name="user" />
邮件: <input type="text" name="email" />
<input type="button" value="提交"/>
<input type="radio" name="sex" value="男"/>男
<input type="radio" name="sex" value="女"/>女
<input type="button" value="submit"/>
</form>
<div id="box"></div>
<script>
$(function () {
$("form input[name=sex]").click(function () {
$('#box').html(decodeURIComponent($(this).serialize()));
})
})
</script>
</body>
传统AJAX有如下问题:
1、可以无刷新改变页面内容,但是无法改变页面的url
2、为了更好的可访问性,内容发生改变后,通常改变URL的hash
3、hash的方法不能很好的处理浏览器的前进,后退和相关的问题
4、进而浏览器引入了onhashchange的接口,不支持浏览器只能定时去判断hash时候改变
5、但这种方式对搜索引擎很不友好
6、twitter和google约定了使用#!xxx(即hash第一个字符为!),搜索引擎进行支持