


Detailed example of js combined with json to implement ajax simple example
This article mainly introduces in detail the relevant information on simple examples of ajax implemented by combining js with json. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.
Preparation
1. Install wampserver or other similar software to build a local integrated installation environment. I installed phpstudy
2. HTML, js, css and other files need to be placed in PHPstudy In the WWW directory, the default run index page
3, bootstrap.css
interface screenshot:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <style> .container{ width: 50%; margin-top: 30px; } .text-danger{ margin-top: 6px; } </style> </head> <body> <p class="container"> <p class="panel panel-default"> <p class="panel-heading"> <p class="panel-title">员工查询</p> </p> <p class="panel-body"> <p class="form-horizontal"> <p class="form-group"> <label class="col-md-2 control-label">员工编号:</label> <p class="col-md-8"> <input type="text" class="form-control" id="keyword"> </p> <p class="col-md-1"> <button class="btn btn-primary" id="search">查询</button> </p> </p> <p class="form-group"> <label class="col-md-2 control-label">查询结果:</label> <p class="text-danger col-md-8" id="searchResult"></p> </p> </p> </p> </p> </p> <p class="container"> <p class="panel panel-default"> <p class="panel-heading"> <p class="panel-title">员工增加</p> </p> <p class="panel-body"> <p class="form-horizontal"> <p class="form-group"> <label class="col-md-2 control-label">员工编号:</label> <p class="col-md-8"> <input type="text" class="form-control" id="add-number"> </p> </p> <p class="form-group"> <label class="col-md-2 control-label">员工姓名:</label> <p class="col-md-8"> <input type="text" class="form-control" id="add-name"> </p> </p> <p class="form-group"> <label class="col-md-2 control-label">员工性别:</label> <p class="col-md-8"> <input type="text" class="form-control" id="add-sex"> </p> </p> <p class="form-group"> <label class="col-md-2 control-label">员工职位:</label> <p class="col-md-8"> <input type="text" class="form-control" id="add-job"> </p> </p> <p class="form-group"> <p class="col-md-offset-2 col-md-1"> <button class="btn btn-primary" id="add-search">增加员工</button> </p> </p> <p class="form-group"> <label class="col-md-2 control-label">结果:</label> <p class="text-danger col-md-8" id="add-resultshow"></p> </p> </p> </p> </p> </p> <script src="staffManage.js"></script> </body> </html>
staffManage.js
Instancing Ajax can be divided into five Click, it’s easier to remember:1. New an XMLHttpRequest instance
Note that it is compatible with lower versions of IE browsers
var xhr; if (window.XMLHttpRequest) { xhr= new XMLHttpRequest(); } else { xhr= new ActiveXObject(‘Microsoft.XMLHTTP'); }
2. open(method,url,asyn)
The open() method of the XMLHttpRequest object has 3 parameters, The first parameter specifies whether it is GET or POST, the second parameter specifies the URL address, and the third parameter specifies whether to use asynchronous. The default is true, so there is no need to write it.
4. send Call the send() method to actually send the request. GET requests do not require parameters, and POST requests require the body part to be passed in as a string or FormData object.
5, onReadyStateChange
6, responseText
// 查询员工方法 var oKeyword=document.getElementById('keyword'), //员工编号 oSearchBtn=document.getElementById('search'), //查询按钮 oSearchRes=document.getElementById('searchResult'); //反馈结果显示 // 查询员工按钮点击事件 oSearchBtn.onclick=function(){ searchStaff(); } // 创建查询员工方法 function searchStaff(){ //var xhr=new XMLHttpRequest(); //标准写法和IE写法混在一起,可以兼容低版本的IE浏览器 var xhr; if (window.XMLHttpRequest) { xhr= new XMLHttpRequest(); } else { xhr= new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open('GET','serverjson.php?number='+oKeyword.value); xhr.send(); //当创建了XMLHttpRequest对象后,要先设置onreadystatechange的回调函数。在回调函数中,通常我们只需通过readyState === 4判断请求是否完成,如果已完成,再根据status === 200判断是否是一个成功的响应。 xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status=200){ var data=JSON.parse(xhr.responseText); //json解析方法JSON.parse 或者 eval('('+xhr.responseText+')') oSearchRes.innerHTML=data.msg; } } } } // 增加员工 var oAddnumber=document.getElementById('add-number'), //员工编号 oAddname=document.getElementById('add-name'), //员工姓名 oAddsex=document.getElementById('add-sex'), //员工性别 oAddjob=document.getElementById('add-job'), //员工职位 oAddSearch=document.getElementById('add-search'), //增加员工按钮 oAddResult=document.getElementById('add-resultshow'); //反馈结果显示 // 增加员工按钮点击事件 oAddSearch.onclick=function(){ createStaff(); } // 创建增加员工方法 function createStaff(){ var xhr; if(xhr.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open('POST','serverjson.php'); //这里注意key=value的等于号两边不要出现空格,会出现错误 var data='name='+oAddname.value +'&number='+oAddnumber.value +'&sex='+oAddsex.value +'&job='+oAddjob.value; //在open和send之间设置Content-Type xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(data); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status=200){ var data=JSON.parse(xhr.responseText); if(data.success){ oAddResult.innerHTML=data.msg; }else{ oAddResult.innerHTML='出现错误:'+data.msg; } }else{ alert('发生错误!'+xhr.status) } } } }
<?php //设置页面内容是html编码格式是utf-8 header("Content-Type: text/plain;charset=utf-8"); //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" => "总经理"), array("name" => "郭靖", "number" => "102", "sex" => "男", "job" => "开发工程师"), array("name" => "黄蓉", "number" => "103", "sex" => "女", "job" => "产品经理") ); //判断如果是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"] . ' 信息保存成功!"}'; } ?>
Summary
The whole process is roughly as shown in the figure:How to implement AJAX and JSONP with native JS
How to use native JS to implement Ajax's GET POST request
Two methods for jquery to implement ajax submission form
The above is the detailed content of Detailed example of js combined with json to implement ajax simple example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

I'm really sorry that I can't provide real-time programming guidance, but I can provide you with a code example to give you a better understanding of how to use PHP to implement SaaS. The following is an article within 1,500 words, titled "Using PHP to implement SaaS: A comprehensive analysis." In today's information age, SaaS (Software as a Service) has become the mainstream way for enterprises and individuals to use software. It provides a more flexible and convenient way to access software. With SaaS, users don’t need to be on-premises
