jQuery Ajax請求后台數據並在前台接收


1.ajax基本語法

<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的數據
  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>

2. php端的接收方法

<!--?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數據
?>

3.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><!-- 用以顯示返回來的數據,只刷新這部分地方 -->
</body>
<script src="//cdn.bootcss.com/jquery/3.0.0-alpha1/jquery.min.js"></script>
</html>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM