Home Web Front-end JS Tutorial Data interaction implementation of Ajax+PHP

Data interaction implementation of Ajax+PHP

Apr 03, 2018 am 11:38 AM
php accomplish

This time I will bring you the data interaction implementation of Ajax+PHP. What are the precautions for the implementation of Ajax+PHP 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 free 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 below. 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:

How to use native ajax to process json data

##How to implement the map interface using the database+ajax method

The above is the detailed content of Data interaction implementation of Ajax+PHP. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

See all articles