使用Ajax的几种方式
原生Ajax
<html>
<body>
输入用户名:<input type="text"/>单击检查按钮后,立即查检结果
<input type="button" value="检查"/>
<hr/>
<div>
</div>
<script type="text/javascript">
document.getElementsByTagName("input")[1].onclick=function(){
var username = document.getElementsByTagName("input")[0].value;
username = encodeURI(username);
var xhr = createXHR();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
var xmlDocument = xhr.responseXML;
var resElement = xmlDocument.getElementsByTagName("res")[0];
var msg = resElement.firstChild.nodeValue;
var divElement = document.getElementsByTagName("div")[0];
divElement.innerHTML = "<img src='"+msg+"'/>";
}
}
}
xhr.open("post","/day31/PostServlet?time="+new Date().getTime());
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send("username="+username);
}
function createXHR(){
var xhr = null;
try{
xhr = new ActiveXObject("microsoft.xmlhttp");
}catch(e){
try{
xhr = new XMLHttpRequest();
}catch(e){
window.alert("你的浏览器太差");
}
}
return xhr;
}
</script>
</body>
</html>
jQuery.ajax(url,[settings])
$.ajax(选项);
选项:
url:"/store/xxx",
type:"get",
data:"username=tom",
success:function(obj){},
error:function(){},
dataType:"json",
async:true
jQuery.get(url, [data], [callback], [type])
jQuery.post(url, [data], [callback], [type])
$.get(url,params,function(data){},type);
$.post(url,params,function(data){},type);