This time I will show you how Ajax should transmit JSON in actual projects. What are the precautions for Ajax to transmit JSON in actual projects. The following is a practical case, let's take a look.
The previous words
Although the full name of ajax is asynchronous javascript and XML. But currently when using ajax technology, passing JSON has become the de facto standard. Because compared to XML, JSON is simple and convenient. This article rewrites the example in the previous article and uses JSON to transfer data
Front-end page
<!-- 前端页面 --> nbsp;html> <meta> <title>Document</title> <style> body{font-size: 20px;margin: 0;line-height: 1.5;} select,button,input{font-size: 20px;line-height: 1.5;} </style> <h2 id="员工查询">员工查询</h2> <label>请输入员工编号:</label> <input> <button>查询</button> <p></p> <h2 id="员工创建">员工创建</h2><script> /*get*/ //查询 var oSearch = document.getElementById('search'); //get方式添加数据 function addURLParam(url,name,value){ url += (url.indexOf("?") == -1 ? "?" : "&"); url +=encodeURIComponent(name) + "=" + encodeURIComponent(value); return url; } oSearch.onclick = function(){ //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //实际操作 var data = JSON.parse(xhr.responseText); if(data.success){ document.getElementById('searchResult').innerHTML = data.msg; }else{ document.getElementById('searchResult').innerHTML = '出现错误:' +data.msg; } }else{ alert('发生错误:' + xhr.status); } } } //发送请求 var url = 'service.php'; url = addURLParam(url,'number',document.getElementById('keyword').value); xhr.open('get',url,true); xhr.send(); } /*post*/ //创建 var oSave = document.getElementById('save'); //post方式添加数据 function serialize(form){ var parts = [],field = null,i,len,j,optLen,option,optValue; for (i=0, len=form.elements.length; i < len; i++){ field = form.elements[i]; switch(field.type){ case "select-one": case "select-multiple": if (field.name.length){ for (j=0, optLen = field.options.length; j < optLen; j++){ option = field.options[j]; if (option.selected){ optValue = ""; if (option.hasAttribute){ optValue = (option.hasAttribute("value") ? option.value : option.text); } else { optValue = (option.attributes["value"].specified ? option.value : option.text); } parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(optValue)); } } } break; case undefined: //fieldset case "file": //file input case "submit": //submit button case "reset": //reset button case "button": //custom button break; case "radio": //radio button case "checkbox": //checkbox if (!field.checked){ break; } /* falls through */ default: //don't include form fields without names if (field.name.length){ parts.push(encodeURIComponent(field.name) + "=" + encodeURIComponent(field.value)); } } } return parts.join("&"); } oSave.onclick = function(){ //创建xhr对象 var xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } //异步接受响应 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ //实际操作 var data = JSON.parse(xhr.responseText); if(data.success){ document.getElementById('createResult').innerHTML = data.msg; }else{ document.getElementById('createResult').innerHTML = '出现错误:'+data.msg; } }else{ alert('发生错误:' + xhr.status); } } } //发送请求 xhr.open('post','service.php',true); xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); xhr.send(serialize(document.getElementById('postForm'))); } </script>
Terminal page
<?php //用于过滤不安全的字符 function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } //设置页面内容的html编码格式是utf-8 header("Content-Type:application/json;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["REQUEST_METHOD"]返回访问页面使用的请求方法 if($_SERVER["REQUEST_METHOD"] == "GET"){ search(); }else if($_SERVER["REQUEST_METHOD"] == "POST"){ create(); } //通过员工编号搜索员工 function search(){ //检查是否有员工编号的参数 //isset检测变量是否设置;empty判断值是否为空 if(!isset($_GET['number']) || empty($_GET['number'])){ echo '{"success":false,"msg":"参数错误"}'; return; } global $staff; $number = test_input($_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; } echo '{"success":true,"msg":"员工' .test_input($_POST['name']) .'信息保存成功!"}'; } ?>
I believe you have mastered the method after reading the case in this article, please come for more exciting information Pay attention to other related articles on php Chinese website!
Recommended reading:
How to communicate data between C and View
Ajax steps to directly implement the like function Detailed explanation
The above is the detailed content of How should Ajax pass JSON in actual projects. For more information, please follow other related articles on the PHP Chinese website!

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.


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

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Linux new version
SublimeText3 Linux latest version

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