【達達前端】Ajax實戰項目源碼講解(快速入門的實例)Github源碼

file

做者 | Jesksonphp

來源 | 達達前端小酒館html

源碼地址:前端

https://github.com/huangguang...mysql

什麼是Ajax技術?實戰中的運用ajax技術,瞭解先後端交互的方式,瞭解移動端的模式,瞭解H5的新技術,瞭解CSS3的使用,和JQuery的使用。jquery

Ajax技術能夠提升用戶體驗,無刷新的與後臺進行數據的交互,異步的操做方式,能夠不用刷新頁面提升性能。git

瞭解先後端的交互流程,主要分爲三部分,客戶端,服務端,數據庫,環境搭建,wamp,phpMyAdmin。github

file

wamp,window,Apache,mysql,php。web

建立項目:ajax

file

建立一個名爲AjaxItem的小項目算法

file

接下來附上個人代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form>
    用戶名:<input type="text">
    <input type="submit" value="註冊">
</form>
</body>
</html>

運行起來的效果是以下截圖

file

添加一個服務端跳轉的頁面reg.php,服務端要找到輸入框的值

提交表單方式:GET,POST

指定當前頁的編碼

header("Content-type:text/html;charset=utf-8");

鏈接數據庫mysql

$con = mysql_connect();

默認值:config.default.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php">
    用戶名:<input type="text" name="username">
    <input type="submit" value="註冊">
</form>
</body>
</html>
2

get提交的特色:

file

file

post提交的特色:

file

上面截圖能夠看出傳輸數據的區別,咱們通常對於數據的查詢,儘可能採用get的方式,而咱們要對數據的修改,添加或者是刪除,咱們能夠用post比較好一點。

服務端的書寫:

選擇數據庫:mysql_select_db();創建數據庫,建表,鍵字段

指定數據庫的編碼格式

mysql_query("set names utf8");

獲取傳輸數據

$_GET
$_POST

建立數據庫:

file

建立表:

file

file

建立數據

file

sql查詢:

select * from 表 where 字段 = 值
mysql_query
mysql_num_rows

reg.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    用戶名:<input type="text" name="username">
    <input type="submit" value="註冊">
</form>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    用戶名:<input type="text" name="username">
    <input type="submit" value="註冊">
</form>
</body>
</html>

reg.php代碼:

<?php
// 定義編碼格式
header("Content-type:text/html;charset=utf-8");
// 鏈接mysql
$con = mysql_connect("localhost",'root','123456');
mysql_select_db('ajaxitem');
mysql_query('set names utf8');

$username = $_POST['username'];
$sql = "select * from reg where username = '$username'";
$query = mysql_query($sql);

// 如何區分查詢到仍是沒有查詢到呢?
//mysql_num_rows($query);
// 找到爲1,沒有找到爲0

if($query && mysql_num_rows($query)){
 echo "<script>alert('已經有人註冊過了')</script>";
 echo "<script>history.back()</script>";
}else {
$sql = "insert into reg(username) values ('$username')";
$sql = mysql_query($sql);
if($query){
    echo "<script>alert('註冊成功')</script>";
    echo "<script>window.location = 'index.html'</script>";
}
}
?>

file

: 3

sql查詢:

select * from 表 where 字段 = 值
mysql_query
mysql_num_rows

sql添加

insert into 表(字段)values(值)

Ajax基本使用:

XMLHttpRequest
open
onreadystatechange

readyState
0未初始化
1初始化
2發送數據
3數據傳送中
4完成

send
onreadystatechange

status
http狀態碼
200
301
304
403
404
500

statusText
responseText
 responseXML
 JSON.parse

POST方式:
須要設置頭信息
位置在send前

setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
setRequestHeader(‘Content-Type’, ‘application/json’);

JSON_stringify
JQuery中的Ajax

$.ajax

url
type
data
success
error
dataType
async

提供公共代碼

require_once()

獲取數據
mysql_fetch_row
mysql_fetch_assoc
mysql_fetch_array
mysql_fetch_object

增刪改查
delete from 表 where 字段 = 值
update 表 set 字段 = 新值 where id = $id;
Functions to create xhrs

function createStandardXHR() {
 try {
  return new window.XMLHttpRequest();
 }catch(e){}
}

function createActiveXHR() {
 try {
  return new window.ActiveXObject("Microsoft.XMLHTTP");
  }catch(e){}
}

index.html代碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    用戶名:<input type="text" name="username">
    <input type="submit" value="註冊">
</form>
<div id="div">

</div>
<script>
var oInput = document.getElementById("input1");
var oDiv = document.getElementById('div1');

oInput.onblur = function () {
    var xhr = new XMLHttpRequest();
    xhr.open('POST','user.php',true);

}
</script>
</body>
</html>

user.php

<?php
// 定義編碼格式
header("Content-type:text/html;charset=utf-8");
// 鏈接mysql
$con = mysql_connect("localhost",'root','123456');
mysql_select_db('ajaxitem');
mysql_query('set names utf8');

$username = $_GET['username'];
$sql = "select * from reg where username = '$username'";
$query = mysql_query($sql);

if($sql && mysql_num_rows($query)){
    echo '{"code":0, "message": "已經有人註冊過啦" }';
}else {
    echo  '{"code":1,"message":"能夠註冊"}';
}
?>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    用戶名:<input type="text" name="username">
    <input type="submit" value="註冊">
</form>
<div id="div">

</div>
<script>
var oInput = document.getElementById("input1");
var oDiv = document.getElementById('div1');

oInput.onblur = function () {
    var xhr = new XMLHttpRequest();
    // xhr.open('POST','user.php?username='+encodeURIComponent(this.value),true);
    xhr.open('POST','user.php',true);

    // 監聽整個流程,屢次觸發
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                xhr.responseText;
                // xhr.responseXML
                // console.log(JSON.parse(xhr.responseText));
                var obj = JSON.parse(xhr.responseText);
                if(obj.code) {
                    oDiv.innerHTML = obj.message
                }else {
                    oDiv.innerHTML = obj.message
                }
            }
        }
    };
    // xhr.send(null);
    xhr.send('username'+encodeURIComponent(this.value));
}
</script>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="reg.php" method="post">
    用戶名:<input type="text" name="username">
    <input type="submit" value="註冊">
</form>
<div id="div">

</div>
<script>
var oInput = document.getElementById("input1");
var oDiv = document.getElementById('div1');

oInput.onblur = function () {
    var xhr = new XMLHttpRequest();
    // xhr.open('POST','user.php?username='+encodeURIComponent(this.value),true);
    xhr.open('POST','user.php',true);

    // 監聽整個流程,屢次觸發
    xhr.onreadystatechange = function () {
        if(xhr.readyState == 4) {
            if(xhr.status == 200) {
                xhr.responseText;
                // xhr.responseXML
                // console.log(JSON.parse(xhr.responseText));
                var obj = JSON.parse(xhr.responseText);
                if(obj.code) {
                    oDiv.innerHTML = obj.message
                }else {
                    oDiv.innerHTML = obj.message
                }
            }
        }
    };
    // xhr.send(null);
    // xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    // xhr.send('username'+encodeURIComponent(this.value));

    // 'username=dada&age=12'
    // xhr.setRequestHeader('Content-Type','application/json');
    // xhr.send('{ "username": dada, "age": 12}');
    // xhr.send(JSON.stringify({"username":"dada","age":12}));

    // {"username":"dada","age":12} -> $.param() -> "useranme=dada&age=12"
}
</script>
</body>
</html>

JQuery:

if(s.data && s.processData && typeof s.data !== "string"){
 s.data = JQuery.param(s.data, s.traditional);
}

inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);

if(state === 2){
return jqXHR;
}

ajax.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
$.ajax({
 url: 'jquery.php',
 type:  'GET',
 data: {username: "dada"},
 success: function(data){
  console.log(data);
 }
});
</body>
</html>

jquery.php

<?PHP

  //echo 'red';
  echo '{"color":"red","width":"200px"}';

?>

請求相同部分:

require_once(‘connect.php');

ajax1.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>
<script>
//get : http://localhost/reg.php?username=dada
//post : http://localhost/reg.php
</script>
</head>

<body>
<form action="reg.php" method="post">
  用戶名 : <input type="text" name="username">   <!--username=dada-->
    <input type="submit" value="註冊">
</form>
</body>
</html>

ajax2.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>

</head>

<body>
<form action="reg.php" method="post">
  用戶名 : <input id="input1" type="text" name="username">   <!--username=dada-->
    <input type="submit" value="註冊">
</form>
<div id="div1"></div>
<script>
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');

oInput.onblur = function(){
  var xhr = new XMLHttpRequest();
  xhr.open('GET','user.php?username='+encodeURIComponent(this.value),true);
  xhr.onreadystatechange = function(){
    
    if(xhr.readyState == 4){
      //console.log(xhr.status);
      //console.log(xhr.statusText);
      if(xhr.status == 200){
        //console.log(xhr.responseText);
        //console.log(JSON.parse(xhr.responseText));
        var obj = JSON.parse(xhr.responseText);
        if(obj.code){
          oDiv.innerHTML = obj.message;
        }
        else{
          oDiv.innerHTML = obj.message;
        }
      }
    }
    
  };
  xhr.send(null);
};
</script>
</body>
</html>

ajax3.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>

</head>

<body>
<form action="reg.php" method="post">
  用戶名 : <input id="input1" type="text" name="username">   <!--username=dada-->
    <input type="submit" value="註冊">
</form>
<div id="div1"></div>
<script>
var oInput = document.getElementById('input1');
var oDiv = document.getElementById('div1');

oInput.onblur = function(){
  var xhr = new XMLHttpRequest();
  xhr.open('POST','user.php',true);
  xhr.onreadystatechange = function(){
    
    if(xhr.readyState == 4){
      //console.log(xhr.status);
      //console.log(xhr.statusText);
      if(xhr.status == 200){
        //console.log(xhr.responseText);
        //console.log(JSON.parse(xhr.responseText));
        var obj = JSON.parse(xhr.responseText);
        if(obj.code){
          oDiv.innerHTML = obj.message;
        }
        else{
          oDiv.innerHTML = obj.message;
        }
      }
    }
    
  };
  //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  //xhr.send('username='+encodeURIComponent(this.value));
  
  //'username=dada&age=12'
  
  //xhr.setRequestHeader('Content-Type', 'application/json');
  //xhr.send('{"username":"dada","age":12}');
  //xhr.send(JSON.stringify({"username":"dada","age":12}));
  
  //{"username":"dada","age":12} ->  $.param()  ->  'username=dada&age=12'
  
};
</script>
</body>
</html>

ajax4.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>
<script src="jquery-2.1.3.min.js"></script>
<script>

$.ajax({
  url : 'jquery.php',
  type : 'POST',
  data : {username:"dada"},
  dataType : 'json',
  async : false,
  success : function(data){   //xhr.responseText
    console.log(data);
    //var obj = JSON.parse(data);
    //console.log(obj);
  },
  error : function(err){
    console.log(err.status);
    console.log(err.statusText);
  }
});
console.log(123);
</script>
</head>

<body>
</body>
</html>

ajax5.html

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>無標題文檔</title>
<script src="jquery-2.1.3.min.js"></script>
<script>

$.ajax({
  url : 'data.php',
  type : 'POST',
  data : {username:"dada"},
  dataType : 'json',
  async : false,
  success : function(data){   //xhr.responseText
    console.log(data);
    //var obj = JSON.parse(data);
    //console.log(obj);
  },
  error : function(err){
    console.log(err.status);
    console.log(err.statusText);
  }
});
console.log(123);
</script>
</head>

<body>
</body>
</html>

connect.php

<?PHP

  header("Content-type: text/html; charset=utf-8");
  $con = mysql_connect('localhost','root','');
  mysql_select_db('ajaxitem');
  mysql_query('set names utf8');

?

data.php

<?PHP

  require_once('connect.php');
  
  //$sql = "delete from reg where username = 'da1'";
  //$query = mysql_query($sql);
  
  $sql = "update reg set username = 'da1' where id = 4";
  $query = mysql_query($sql);
  
  $sql = "select * from reg limit 2";
  $query = mysql_query($sql);
  
  //print_r($query);
  //print_r(mysql_num_rows($query));
  
  //$row = mysql_fetch_row($query);
  //print_r($row);
  
  /*while($row = mysql_fetch_row($query)){    //數組下標的方式輸入
    print_r($row);
  }*/
  
  /*while($row = mysql_fetch_assoc($query)){    //數組鍵值的方式輸入
    print_r($row);
  }*/
  
  /*while($row = mysql_fetch_array($query)){    //數組總體的方式輸入
    print_r($row);
  }*/
  
  /*while($row = mysql_fetch_object($query)){    //對象鍵值的方式輸入
    print_r($row);
  }*/
  /*while($row = mysql_fetch_assoc($query)){    //數組鍵值的方式輸入
    print_r($row['username']);
  }*/
  /*while($row = mysql_fetch_object($query)){    //對象鍵值的方式輸入
    print_r($row -> username);
  }*/
  while($row = mysql_fetch_assoc($query)){    //數組鍵值的方式輸入
    $data[] = $row;
  }
  
  //print_r(json_encode($data));
  
  echo json_encode($data);
  
?>

user.php

<?PHP

  require_once('connect.php');
  
  $username = $_REQUEST['username'];
  
  $sql = "select * from reg where username = '$username'";
  $query = mysql_query($sql);
  
  if($query && mysql_num_rows($query)){
    echo '{"code":0 , "message" : "已經有人註冊過啦"}'; 
  }
  else{
    echo '{"code":1 , "message" : "能夠註冊"}'; 
  }

?>

jquery.php

<?PHP

  //echo 'red';
  echo '{"color":"red","width":"200px"}';

?>

reg.php

<?PHP

  //username -> hello
  
  require_once('connect.php');

  $username = $_POST['username'];
  $sql = "select * from reg where username = '$username'";
  $query = mysql_query($sql);
    
  if($query && mysql_num_rows($query)){
    echo "<script>alert('已經有人註冊過啦')</script>";
    echo "<script>history.back()</script>";
  }
  else{
    $sql = "insert into reg(username) values('$username')";
    $query = mysql_query($sql);
    if($query){
      echo "<script>alert('註冊成功')</script>";
      echo "<script>window.location = 'index.html'</script>";
    }
  }

?>

總結

在博客平臺裏,將來的路還很長,也但願本身之後的文章你們能多多支持,多多批評指正,咱們一塊兒進步,一塊兒走花路。

很是感謝讀者能看到這裏,若是這個文章寫得還不錯,以爲「達達」我有點東西的話,以爲我可以堅持的學習,以爲此人能夠交朋友的話, 求點贊👍 求關注❤️ 求分享👥 對暖男我來講真的

很是有用!!!

❤️ 不要忘記留下你學習的腳印 [點贊 + 收藏 + 評論]

做者Info:

【做者】:Jeskson
【原創公衆號】:達達前端小酒館。
【福利】:公衆號回覆 「資料」 送自學資料大禮包(進羣分享,想要啥就說哈,看我有沒有)!
【轉載說明】:轉載請說明出處,謝謝合做!~

大前端開發,定位前端開發技術棧博客,PHP後臺知識點,web全棧技術領域,數據結構與算法、網絡原理等通俗易懂的呈現給小夥伴。謝謝支持,承蒙厚愛!!!


若本號內容有作得不到位的地方(好比:涉及版權或其餘問題),請及時聯繫咱們進行整改便可,會在第一時間進行處理。


請點贊!由於大家的贊同/鼓勵是我寫做的最大動力!

歡迎關注達達的CSDN!

這是一個有質量,有態度的博客

前端技術棧

相關文章
相關標籤/搜索