Ajax+php數(shù)據(jù)交互并且局部刷新頁面的實(shí)現(xiàn)詳解
什么是Ajax?
國內(nèi)翻譯常為“阿賈克斯”和阿賈克斯足球隊(duì)同音,AJAX 是一種用于創(chuàng)建快速動態(tài)網(wǎng)頁的技術(shù),他不是新語言,而是一種使用現(xiàn)有標(biāo)準(zhǔn)的新方法。通過在后臺與服務(wù)器進(jìn)行少量數(shù)據(jù)交換,AJAX 可以使網(wǎng)頁實(shí)現(xiàn)異步更新,這樣就可以在不重新加載整個網(wǎng)頁的情況下,對網(wǎng)頁的某部分進(jìn)行更新。
XMLHttpRequest 是 AJAX 的基礎(chǔ),用于和服務(wù)器交換數(shù)據(jù)。所有現(xiàn)代瀏覽器均支持 XMLHttpRequest 對象(IE5 和 IE6 使用 ActiveXObject)
下面這篇文章主要介紹的是利用ajax實(shí)現(xiàn)與php數(shù)據(jù)交互,并局部刷新頁面的相關(guān)內(nèi)容,下面話不多說,來一起看看詳細(xì)的介紹:
一、語法簡介
1.1 ajax基本語法
$.ajax({
type: "post", //數(shù)據(jù)提交方式(post/get)
url: "http://xxx/test/demo.php", //提交到的url
data: {username:username,password:password},//提交的數(shù)據(jù)
dataType: "json", //返回的數(shù)據(jù)類型格式
success: function(msg){
...//返回成功的回調(diào)函數(shù)
},
error:function(msg){
...//返回失敗的回調(diào)函數(shù)
}
});
1.2 php端的接收方法
<!--?php $username=$_POST['username']; //接收以post方式提交來的username數(shù)據(jù) $password=$_POST['password']; ?>
二、示例詳解
2.1 html端代碼demo.html
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>ajaxTest</title> </head> <body> <input type="text" id="username"> <input type="text" id="password"> <button id="sub">查詢</button> <span id="text"></span><!-- 用以顯示返回來的數(shù)據(jù),只刷新這部分地方 --> </body> <script src="http://cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script> </html>
2.2 在demo.html中加入以下js代碼
<script>
$(function(){
$('#sub').click(function(){
var username=$('#username').val();
var password=$('#password').val();
$.ajax({
type: "post",
url: "http://xxx/test/demo.php",
data: {username:username,password:password}, //提交到demo.php的數(shù)據(jù)
dataType: "json", //回調(diào)函數(shù)接收數(shù)據(jù)的數(shù)據(jù)格式
success: function(msg){
$('#text').empty(); //清空Text里面的所有內(nèi)容
var data='';
if(msg!=''){
data = eval("("+msg+")"); //將返回的json數(shù)據(jù)進(jìn)行解析,并賦給data
}
$('#text').html("用戶名為:" + data.username + ",密碼為:" + data.password); //在#text中輸出
console.log(data); //控制臺輸出
},
error:function(msg){
console.log(msg);
}
});
});
})
</script>
2.3 php端代碼demo.php
<!--?php
header('Content-type:text/json;charset=utf-8');
$username=$_POST['username'];
$password=$_POST['password'];
$data='{username:"' . $username . '",password:"' . $password .'"}';//組合成json格式數(shù)據(jù)
echo json_encode($data);//輸出json數(shù)據(jù)
?>
三、最終效果如下

demo下載地址
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Ajax獲得站點(diǎn)文件內(nèi)容實(shí)例不涉及服務(wù)器
選擇一部著作,會通過 Ajax 實(shí)時獲得相關(guān)的名字,一個簡單的不涉及服務(wù)器的Ajax實(shí)例,需要的朋友可以參考下2014-05-05
jQuery+Ajax實(shí)現(xiàn)表格數(shù)據(jù)不同列標(biāo)題排序(為表格注入活力)
CSS也使得表格的布局越來越光彩耀人。但是,無論如何,都掩飾不了那些包裝下的死板,接下來為大家介紹下讓那些死板的數(shù)據(jù) 更具有可讀性、可用性2013-04-04
IE瀏覽器與FF瀏覽器關(guān)于Ajax傳遞參數(shù)值為中文時的區(qū)別實(shí)例分析
這篇文章主要介紹了IE瀏覽器與FF瀏覽器關(guān)于Ajax傳遞參數(shù)值為中文時的區(qū)別,結(jié)合實(shí)例分析說明了ajax參數(shù)傳遞過程中的參數(shù)轉(zhuǎn)碼相關(guān)注意事項(xiàng)與使用技巧,需要的朋友可以參考下2015-12-12

