欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Ajax+php數(shù)據(jù)交互并且局部刷新頁面的實現(xiàn)詳解

 更新時間:2017年07月06日 16:45:18   作者:andersonyan  
這篇文章主要給大家介紹了關(guān)于利用Ajax與php數(shù)據(jù)交互并且局部刷新頁面的實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家具有一定的參考學(xué)習(xí)價值,需要的朋友們下面跟著小編一起來學(xué)習(xí)學(xué)習(xí)吧。

什么是Ajax?

國內(nèi)翻譯常為“阿賈克斯”和阿賈克斯足球隊同音,AJAX 是一種用于創(chuàng)建快速動態(tài)網(wǎng)頁的技術(shù),他不是新語言,而是一種使用現(xiàn)有標準的新方法。通過在后臺與服務(wù)器進行少量數(shù)據(jù)交換,AJAX 可以使網(wǎng)頁實現(xiàn)異步更新,這樣就可以在不重新加載整個網(wǎng)頁的情況下,對網(wǎng)頁的某部分進行更新。

XMLHttpRequest 是 AJAX 的基礎(chǔ),用于和服務(wù)器交換數(shù)據(jù)。所有現(xiàn)代瀏覽器均支持 XMLHttpRequest 對象(IE5 和 IE6 使用 ActiveXObject)

下面這篇文章主要介紹的是利用ajax實現(xiàn)與php數(shù)據(jù)交互,并局部刷新頁面的相關(guān)內(nèi)容,下面話不多說,來一起看看詳細的介紹:

一、語法簡介

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ù)進行解析,并賦給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下載地址

下載demo

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。

相關(guān)文章

最新評論