天天看點

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

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

作者 |  Jeskson

2019年12月28日

1源碼位址:

https://github.com/huangguangda/Ajaxitm什麼是Ajax技術?實戰中的運用ajax技術,了解前後端互動的方式,了解移動端的模式,了解H5的新技術,了解CSS3的使用,和JQuery的使用。Ajax技術可以提高使用者體驗,無重新整理的與背景進行資料的互動,異步的操作方式,可以不用重新整理頁面提高性能。了解前後端的互動流程,主要分為三部分,用戶端,服務端,資料庫,環境搭建,wamp,phpMyAdmin。

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

wamp,window,Apache,mysql,php。建立項目:

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

建立一個名為AjaxItem的小項目

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

接下來附上我的代碼

<!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>      

運作起來的效果是如下截圖

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

添加一個服務端跳轉的頁面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送出的特點:

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

post送出的特點:

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

上面截圖可以看出傳輸資料的差別,我們一般對于資料的查詢,盡量采用get的方式,而我們要對資料的修改,添加或者是删除,我們可以用post比較好一點。服務端的書寫:選擇資料庫:mysql_select_db();建立資料庫,建表,鍵字段指定資料庫的編碼格式mysql_query("set names utf8");擷取傳輸資料

$_GET$_POST      

建立資料庫:

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

建立表:

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

建立資料

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

sql查詢:

select * from 表 where 字段 = 值mysql_querymysql_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>";}}?>      
【達達前端】Ajax實戰項目源碼講解(快速入門的執行個體)Github源碼

3

select * from 表 where 字段 = 值mysql_querymysql_num_rows
sql添加insert into 表(字段)values(值)      

Ajax基本使用:

XMLHttpRequestopenonreadystatechange
readyState0未初始化1初始化2發送資料3資料傳送中4完成
send      
onreadystatechange
statushttp狀态碼200301304403404500
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
urltypedatasuccesserrordataTypeasync      

提供公共代碼

require_once()
擷取資料mysql_fetch_rowmysql_fetch_assocmysql_fetch_arraymysql_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":"可以注冊"}';}?>      
<!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>      
<!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);  ?>      
<?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" : "可以注冊"}';   }
?>      
<?PHP
  //echo 'red';  echo '{"color":"red","width":"200px"}';
?>      
<?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>";    }  }
?>      

總結

在部落格平台裡,未來的路還很長,也希望自己以後的文章大家能多多支援,多多批評指正,我們一起進步,一起走花路。非常有用!!!

一名喜愛程式設計技術與專注于前端的程式員,将web前端領域、資料結構與算法、網絡原理等通俗易懂的呈現給小夥伴。分享web前端相關的技術文章、工具資源,精選課程、熱點資訊。

推薦閱讀

1、你知道多少this,new,bind,call,apply?那我告訴你

2、為什麼學習JavaScript設計模式,因為它是核心

3、一篇文章把你帶入到JavaScript中的閉包與進階函數

4、大廠HR面試ES6中的深入淺出面試題知識點

意見回報