Home > Web Front-end > JS Tutorial > body text

Ajax+PHP for data interaction (with code)

php中世界最好的语言
Release: 2018-04-25 16:04:04
Original
2331 people have browsed it

This time I will bring you Ajax PHP for data interaction (with code). What are the precautions for Ajax PHP for data interaction? . The following is a practical case, let's take a look.

PHP is a server-side scripting language for creating dynamic interactive sites. Advantages: PHP scripting language is widely used, open source and free. The most important thing is that it is easy to get started and easy to master.

PHP can generate dynamic page content

PHP can create, open, read, write, delete and close files on the server

PHP can receive form data

PHP can send and retrieve cookies

PHP can add, delete, and modify data in the database

PHP can restrict users from accessing certain pages in the website

Can run on various platforms, compatible with almost all WEB servers, and supports multiple databases

1. If we want to run PHP, we must first have a web server. Generally, a server can be deployed locally for testing. So we need to download XAMPP. We search apache friends on Baidu, open the first link directly, and then download the latest version (PHP7.0.9) without hesitation, and install it after downloading.

2.

2. Now configure XAMPP to deploy a local server. To open it, you only need to enable the Apache service. I will start it successfully. . If the activation is unsuccessful and no data is displayed in Port(s), it means that the PC port you are listening on is occupied. You can change the listening port in the first option of Config, find the Listen 8080 command in Notepad and change the suffix. Here I changed the listening port to the idle 8080.

3. Next, open Dreamweaver to build a server site. Site configuration: The local site folder must be selected in the htdocs directory of the path where you installed Xampp.

4. Add server configuration:

The site is set up , and then create server.php in the site folder. The script is as follows

<?php
//设置页面内容是html编码格式是utf-8
//header("Content-Type: text/plain;charset=utf-8"); 
header(&#39;Access-Control-Allow-Origin:*&#39;);
header(&#39;Access-Control-Allow-Methods:POST,GET&#39;);
header(&#39;Access-Control-Allow-Credentials:true&#39;); 
header("Content-Type: application/json;charset=utf-8"); 
//header("Content-Type: text/xml;charset=utf-8"); 
//header("Content-Type: text/html;charset=utf-8"); 
//header("Content-Type: application/javascript;charset=utf-8");
//定义一个多维数组,包含员工的信息,每条员工信息为一个数组
$staff = array
(
array("name" => "乔布斯", "number" => "101", "sex" => "男", "job" => "IOS开发工程师"),
array("name" => "比尔盖茨", "number" => "102", "sex" => "男", "job" => "微软开发工程师"),
array("name" => "陈美丽", "number" => "103", "sex" => "女", "job" => "安卓开发工程师"),
array("name" => "黄力", "number" => "104", "sex" => "男", "job" => "Java开发工程师"),
array("name" => "车神", "number" => "105", "sex" => "男", "job" => "游戏开发工程师"),
array("name" => "测试猫", "number" => "106", "sex" => "男", "job" => "web前端开发工程师")
);
//判断如果是get请求,则进行搜索;如果是POST请求,则进行新建
//$_SERVER是一个超全局变量,在一个脚本的全部作用域中都可用,不用使用global关键字
//$_SERVER["REQUEST_METHOD"]返回访问页面使用的请求方法
if ($_SERVER["REQUEST_METHOD"] == "GET") {
search();
} elseif ($_SERVER["REQUEST_METHOD"] == "POST"){
create();
}
//通过员工编号搜索员工
function search(){
//检查是否有员工编号的参数
//isset检测变量是否设置;empty判断值为否为空
//超全局变量 $_GET 和 $_POST 用于收集表单数据
if (!isset($_GET["number"]) || empty($_GET["number"])) {
echo '{"success":false,"msg":"参数错误"}';
return;
}
//函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。
//global 关键词用于访问函数内的全局变量
global $staff;
//获取number参数
$number = $_GET["number"];
$result = '{"success":false,"msg":"没有找到员工。"}';
//遍历$staff多维数组,查找key值为number的员工是否存在,如果存在,则修改返回结果
foreach ($staff as $value) {
if ($value["number"] == $number) {
$result = '{"success":true,"msg":"找到员工:员工编号:' . $value["number"] . 
',员工姓名:' . $value["name"] . 
',员工性别:' . $value["sex"] . 
',员工职位:' . $value["job"] . '"}';
break;
}
}
 echo $result;
}
//创建员工
function create(){
//判断信息是否填写完全
if (!isset($_POST["name"]) || empty($_POST["name"])
|| !isset($_POST["number"]) || empty($_POST["number"])
|| !isset($_POST["sex"]) || empty($_POST["sex"])
|| !isset($_POST["job"]) || empty($_POST["job"])) {
echo '{"success":false,"msg":"参数错误,员工信息填写不全"}';
return;
}
//TODO: 获取POST表单数据并保存到数据库
//提示保存成功
echo '{"success":true,"msg":"员工:' . $_POST["name"] . ' 信息保存成功!"}';
}
?>
Copy after login

We can query the data in the server.php file array $staff, and can implement the function of adding data. Let’s create a demo. html

<style>
body,input,button,select,h1{
font-size:20px;
line-height:18px;
}
</style>
<script>
window.onload=function(){
document.getElementById("search").onclick=function(){//查询数据
//发送Ajax查询请求并处理
var request=new XMLHttpRequest();
//open("方法(GET查询,POST添加)","打开的文件数据",处理方式(同步为false异步为true,不填默认为true));
request.open("GET","server.php?number="+document.getElementById('keyword').value);
request.send();
request.onreadystatechange=function(){
if(request.readyState===4){//当服务器请求完成
if(request.status===200){//status==200为服务器请求成功
 var data=JSON.parse(request.responseText);
 if(data.success){//数据填写符合要求
document.getElementById('searchResult').innerHTML=data.msg;
 }else{//数据填写不符号要求
document.getElementById('searchResult').innerHTML="出现错误:"+data.msg;
 } 
}else{//服务器请求失败
 alert("发生错误:"+request.status);
}
}
}
}
document.getElementById("save").onclick=function(){//添加数据
//发送Ajax添加数据请求并处理
var request=new XMLHttpRequest();
//open("方法(GET查询,POST添加)","打开的文件数据",处理方式(同步为false异步为true,不填默认为true));;
request.open("POST","server.php");
//定义data取得用户所填写的数据,并且send(data)到服务器
var data="name="+document.getElementById("staffName").value
 +"&number="+document.getElementById("staffNumber").value
 +"&sex="+document.getElementById("staffSex").value
 +"&job="+document.getElementById("staffJob").value;
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//在POST方法里必写,否则添加数据不起作用
request.send(data);
request.onreadystatechange=function(){
if(request.readyState===4){//当服务器请求完成
if(request.status===200){//status==200为服务器请求成功
 var data=JSON.parse(request.responseText);
 if(data.success){//数据填写符合要求
document.getElementById('createResult').innerHTML=data.msg;
 }else{//数据填写不符合要求
document.getElementById('createResult').innerHTML="出现错误:"+data.msg;
 } 
}else{//服务器请求失败
 alert("发生错误:"+request.status);
}
}
}
}
}
</script>
<body>
<h1>员工查询</h1>
<label>请输入员工编号:</label>
<input type="text" id="keyword"/>
<button id="search">查询</button>
<p id="searchResult"></p>
<h1>员工创建</h1>
<label>请输入员工姓名:</label>
<input type="text" id="staffName"/><br>
<label>请输入员工编号:</label>
<input type="text" id="staffNumber"/><br>
<label>请输入员工性别:</label>
<select id="staffSex">
 <option>男</option>
 <option>女</option>
</select><br>
<label>请输入员工职位:</label>
<input type="text" id="staffJob"/><br>
<button id="save">保存</button>
<p id="createResult"></p>
</body>
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

JQuery json makes Ajax calling function (with code)

Summary of cases using JSONP

The above is the detailed content of Ajax+PHP for data interaction (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!