主要是原生的利用xmlHttpRequest执行Ajax请求、JQuery中的ajax、get、post、load方法。
test.html页面代码:
<html>
<head>
<title>Ajax<title>
<script src="jquery/jquery-1.8.0.js" type="text/javascript" ></script>
<script>
function Ajax(){
var xmlHttpReq =null;
if (window.ActiveXObject){//IE5 IE6是以ActiveXObject的方式引入XMLHttpRequest的
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
else if (window.XMLHttpRequest){//除IE5 IE6 以外的浏览器XMLHttpRequest是window的子对象
xmlHttpReq = new XMLHttpRequest();//实例化一个XMLHttpRequest
}
xmlHttpReq.open("GET","http://127.0.0.1/test.php",true);
xmlHttpReq.onreadystatechange=RequestCallBack;
xmlHttpReq.send(null);
function RequestCallBack(){
if(xmlHttpReq.readyState ==4){
if(xmlHttpReq.status==200){
alert(xmlHttpReq.responseText);
document.getElementById("resText").innerHTML=xmlHttpReq.responseText;
}
}
}
}
$(function(){
$("#get").click(function(){
$.get("http://127.0.0.1/test.php",{name:"eddy"},function(data, textStatus){
$("#resText").html(data);
});
});
$("#post").click(function(){
$.post("http://127.0.0.1/test.php",{name:"eddy"},function(data, textStatus){
$("#resText").html(data);
});
});
$("#ajax").click(function(){
$.ajax({
type:"GET",
url:"http://127.0.0.1/test.php",
data:{name:"eddy"},
success:function(data){
$("#resText").html(data);
}
});
});
$("#load").click(function(){
$("#resText").load("http://127.0.0.1/test.php",function(responseText, textStatus, XMLHttpRequest){
alert(responseText); //请求返回的内容
alert(textStatus); //请求状态:success,error
alert(XMLHttpRequest); //XMLHttpRequest对象);
});
});
})
</script>
</head>
<body>
<input type="button" value="Ajax提交 原生" onclick="Ajax();" />
<input type="button" value="Ajax提交(Jquery-Load)" id="load"/>
<input type="button" value="Ajax提交(Jquery-get)" id="get"/>
<input type="button" value="Ajax提交(Jquery-post)" id="post"/>
<input type="button" value="Ajax提交(Jquery-ajax)" id="ajax"/>
<div id="resText">待更新</div>
</body>
</html>
test.php页面代码:
<?php
echo "Hello, Ajax!","<br />";
if($_GET['name']){
echo $_GET['name'];
}
if($_POST['name']){
echo $_POST['name'];
}
?>
各浏览器的支持情况:
function 跨站请求 IE8 Chrome22 Firefox16
原生Ajax yes success fail fail
原生Ajax no success success success
load() yes fail fail fail
load() no success success success
get() yes fail fail fail
get() no success success success
post() yes fail fail fail
post() no success success success
ajax() yes fail fail fail
ajax() no success success success
已经有(0)位网友发表了评论,你也评一评吧!
原创文章如转载,请注明:转载自Eddy Blog
原文地址:http://www.rrgod.com/webdesign/848.html 欢迎订阅Eddy Blog。
Tags:Ajax