Home Web Front-end JS Tutorial Ajax+PHP for data interaction (with code)

Ajax+PHP for data interaction (with code)

Apr 25, 2018 pm 04:04 PM
php code

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!

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

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,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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

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.

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.

See all articles