Error message here!

Hide Error message here!

忘记密码?

Error message here!

请输入正确邮箱

Hide Error message here!

密码丢失?请输入您的电子邮件地址。您将收到一个重设密码链接。

Error message here!

返回登录

Close

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

达达前端小酒馆 2019-12-29 00:08:00 阅读数:15 评论数:0 点赞数:0 收藏数:0

file

作者 | Jeskson

来源 | 达达前端小酒馆

源码地址:

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

什么是Ajax技术?实战中的运用ajax技术,了解前后端交互的方式,了解移动端的模式,了解H5的新技术,了解CSS3的使用,和JQuery的使用。

Ajax技术可以提高用户体验,无刷新的与后台进行数据的交互,异步的操作方式,可以不用刷新页面提高性能。

了解前后端的交互流程,主要分为三部分,客户端,服务端,数据库,环境搭建,wamp,phpMyAdmin。

file

wamp,window,Apache,mysql,php。

创建项目:

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!

这是一个有质量,有态度的博客

前端技术栈

版权声明
本文为[达达前端小酒馆]所创,转载请带上原文链接,感谢
https://segmentfault.com/a/1190000021431634