假设当前有index.html、demo.js、submit.php。
index.html中有form表单和用于显示回调内容的DIV为:
<form>
用户名:<input type="text" name="user">
邮件:<input type="text" name="email">
<input type="button" value="提交">
</form>
<div id="box"></div>
submit.php中接收和处理的代码为:
<?php
echo $_POST['user'].'-'.$_POST['email'];
?>
ajax代码为demo.js内:
$(function(){
$('form input[type=button]').click(function(){ //绑定form表单下的input中type为button的点击事件
$.ajax({
type:'POST',
url:'submit.php', //脚本的URL地址。
data:$('form').serialize(), //如果是多个form,建议绑定ID处理。serialize()是序列化处理得到的结果。比如填入user="xxx"和email=“xxx,”序列化后的格式为:user="xxx"&email="xxx",序列化后传递给脚本处理(也就是,字符串形式的键值对)。
success:function(response,status,xhr){
$('#box').html(response);//以html形式解析并返回到div id为box中显示。
}
});
});
以上的data:$('form').serialize()
相当于
data:{
user:$('form input['name=user']').val(),
eamil:$('form input['name=email']').val(),
};
当然了,单选框也可以使用:
前面的index.html改写为:
<form>
<input type="radio" name="sex" value=""男>男
<input type="radio" name="sex" value="女">女
<input type="button" value="提交">
</form>
<div id=""box></div>
然后ajax的 demo.js代码为:
$(form input['name=sex']).click(function(){
$(#box).html($(this).serialize()); //获取本身序列化后的值并以html格式显示在box div中,由于序列化后是编码过的,要解码需要用到js,样式为:$(#box).html(decodeURIComponent($(this).serialize()));
})
如果需要转换成json格式的,如下:
$(form input['name=sex']).click(function(){
$(#box).html($(this).serializeArray()); //这样即可转换为json数据。
})
初始化重复的属性:
$.ajaxSetup({
type:'POST',
url:'submit.php',
data:$('form').serialize(),
});
全局加载
当出现网络问题时,虽然使用了ajax异步加载,但会在页面上出现假死状态,没能加载出想要的内容,这时候就需要使用全局加载。显示内容为加载中。。。
假设前面的html文档中加入了<span class="loading">正在加载中...</span>
如:
$(function(){
$('form input[type=button]').click(function(){
$.ajax({
type:'POST',
url:'submit.php',
data:$('form').seriaize(),
success:function(response,status,xhr){
$('#box').html(response);
}
})
})
});
$(document).ajaxStart(function(){
$('.loading').show(); //文件加载的时候,显示正在加载中
}).ajaxStop(function(){
$('.loading').hide(); //加载完成后,隐藏。
})
如果加载不出来,可以设置超时:
$(function(){
$('form input[type=button]').click(function(){
$.ajax({
type:'POST',
url:'submit.php',
data:$('form').seriaize(),
success:function(response,status,xhr){
$('#box').html(response);
},
timeout:3000 //3000毫秒,即三分钟后加载不出来就超时
})
})
});
JSON和JSONP
如果在同域下,只需加入datatype属性,设置好之后就可加载json文件,跨域就需要用JSONP.