前端项目实战ajax,【达达前端】Ajax实战项目源码讲解(快速入门的实例)Github源码...

本文详细介绍了Ajax技术,包括其在前后端交互中的作用,无刷新数据更新,以及GET和POST提交方式的区别。通过实例展示了如何使用Ajax进行数据库操作,并提供了PHP实现的服务器端代码。同时,文章探讨了JQuery中的Ajax用法,以及如何处理响应数据。最后,通过一系列示例代码,解释了Ajax在用户注册场景中的应用。
摘要由CSDN通过智能技术生成

73fcb0cc7cce026d0f40134061f86225.png

作者 |  Jeskson

2019年12月28日

1源码地址:

https://github.com/huangguangda/Ajaxitm什么是Ajax技术?实战中的运用ajax技术,了解前后端交互的方式,了解移动端的模式,了解H5的新技术,了解CSS3的使用,和JQuery的使用。Ajax技术可以提高用户体验,无刷新的与后台进行数据的交互,异步的操作方式,可以不用刷新页面提高性能。了解前后端的交互流程,主要分为三部分,客户端,服务端,数据库,环境搭建,wamp,phpMyAdmin。

2634458e0e1add5ef96ec047a22b6598.png

wamp,window,Apache,mysql,php。创建项目:

39d614af80685cfc067610403c031b3b.png

创建一个名为AjaxItem的小项目

d36bb130049e4185d15d82a41f88e16d.png

接下来附上我的代码

Title 用户名:

运行起来的效果是如下截图

8bb852170c3a1a6033dc9cd5a3e5f5fc.png

添加一个服务端跳转的页面reg.php,服务端要找到输入框的值提交表单方式:GET,POST指定当前页的编码header("Content-type:text/html;charset=utf-8");

连接数据库mysql$con = mysql_connect();

默认值:config.default.php

Title 用户名:

2

get提交的特点:

0c2629a95fed1530e10791bfd9f43dbd.png

5269702f833eb22d92a80f8615785784.png

post提交的特点:

b318712cbd7acc716439c76e804299c3.png

上面截图可以看出传输数据的区别,我们一般对于数据的查询,尽量采用get的方式,而我们要对数据的修改,添加或者是删除,我们可以用post比较好一点。服务端的书写:选择数据库:mysql_select_db();建立数据库,建表,键字段指定数据库的编码格式mysql_query("set names utf8");获取传输数据$_GET$_POST

创建数据库:

f7ea87793e52aa104f8ff8ab20d500d2.png

创建表:

961d0c886b8c0499cd473ab5f5de44ae.png

25c039d203360a1cebe58ac69c52b312.png

创建数据

d686b44c1d8c851d208dfd0ef242104a.png

sql查询:select * from 表 where 字段 = 值mysql_querymysql_num_rows

reg.php

Title 用户名:

index.html

Title 用户名:

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 "alert('已经有人注册过了')"; echo "history.back()";}else {$sql = "insert into reg(username) values ('$username')";$sql = mysql_query($sql);if($query){ echo "alert('注册成功')"; echo "window.location = 'index.html'";}}?>

90c712ece334be5c51bf2dccfc8bae44.png

3

sql查询: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 xhrsfunction createStandardXHR() { try {  return new window.XMLHttpRequest(); }catch(e){}}

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

index.html代码:

Title 用户名:

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

}

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

Title 用户名:

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));}

index.html

Title 用户名:

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"}

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

Title$.ajax({ url: 'jquery.php', type: 'GET', data: {username: "dada"}, success: function(data){ console.log(data); }});

jquery.php<?PHP

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

?>

请求相同部分:require_once(‘connect.php');

ajax1.html

无标题文档//get : http://localhost/reg.php?username=dada//post : http://localhost/reg.php 用户名 :

ajax2.html

无标题文档 用户名 :

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);};

ajax3.html

无标题文档 用户名 :

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' };

ajax4.html

无标题文档

$.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);

ajax5.html

无标题文档

$.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);

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 "alert('已经有人注册过啦')"; echo "history.back()"; } else{ $sql = "insert into reg(username) values('$username')"; $query = mysql_query($sql); if($query){ echo "alert('注册成功')"; echo "window.location = 'index.html'"; } }

?>

总结

在博客平台里,未来的路还很长,也希望自己以后的文章大家能多多支持,多多批评指正,我们一起进步,一起走花路。非常有用!!!

一名喜爱编程技术与专注于前端的程序员,将web前端领域、数据结构与算法、网络原理等通俗易懂的呈现给小伙伴。分享web前端相关的技术文章、工具资源,精选课程、热点资讯。

推荐阅读

意见反馈

若本号内容有做得不到位的地方(比如:涉及版权或其他问题),请及时联系我们进行整改即可,会在第一时间进行处理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值