本文主要有以下幾個要點:
ajax的基本語法結構
jQuery基本語法
json數組基本結構
ajax回調函數中的json數組解析及局部刷新
php基本語法
ajax與php的對接
php中post數據提交方式與接收
ajax基本語法
$.ajax({
type: "post", //數據提交方式(post/get)
url: "demo.php", //提交到的url
data: {username:username,password:password},//提交的數據
dataType: "json",//返回的數據類型格式
success: function(msg){
...//返回成功的回調函數
},
error:function(msg){
...//返回失敗的回調函數
}
});
php端的接收方法
<?php
$username=$_POST['username'];//接收以post方式提交來的username數據
$password=$_POST['password'];
<?php header('Content-type:text/json;charset=utf-8'); $username=$_POST['username']; $password=$_POST['password']; $data='{username:"' . $username . '",password:"' . $password .'"}';//組合成json格式數據 echo json_encode($data);//輸出json數據
<!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><!-- 用以顯示返回來的數據,只刷新這部分地方 --> </body> <script src="//cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script> <script> $(function(){ $('#sub').click(function(){ var username=$('#username').val(); var password=$('#password').val(); $.ajax({ type: "post", url: "demo.php", data: {username:username,password:password},//提交到demo.php的數據 dataType: "json",//回調函數接收數據的數據格式 success: function(msg){ $('#text').empty(); //清空Text里面的所有內容 var data=''; if(msg!=''){ data = eval("("+msg+")"); //將返回的json數據進行解析,並賦給data } $('#text').html("用戶名為:" + data.username + ",密碼為:" + data.password); //在#text中輸出 console.log(data); //控制台輸出 }, error:function(msg){ console.log(msg); } }); }); }) </script> </html>