Home Web Front-end JS Tutorial Ajax passes JSON example code

Ajax passes JSON example code

May 22, 2018 pm 04:35 PM
ajax javascript json

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. This article mainly introduces the Ajax delivery JSON example code. Friends who need it can refer to 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

<!-- 前端页面 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<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>
</head>
<body>
<h2>员工查询</h2>  
<label>请输入员工编号:</label>
<input type="text" id="keyword">
<button id="search">查询</button>
<p id="searchResult"></p>
<h2>员工创建</h2>
<form id="postForm">
  <label>请输入员工姓名:</label>
  <input type="text" name="name"><br>
  <label>请输入员工编号:</label>
  <input type="text" name="number"><br>
  <label>请输入员工性别:</label>
  <select name="sex">
  <option value="男">男</option>
  <option value="女">女</option>
  </select><br>
  <label>请输入员工职位:</label>
  <input type="text" name="job"><br>
  <button id="save" type="button">保存</button>  
</form>
<p id="createResult"></p>
<script>
/*get*/
//查询
var oSearch = document.getElementById(&#39;search&#39;);
//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(&#39;Microsoft.XMLHTTP&#39;);
  }
  //异步接受响应
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status == 200){
        //实际操作
        var data = JSON.parse(xhr.responseText);
        if(data.success){
          document.getElementById(&#39;searchResult&#39;).innerHTML = data.msg;
        }else{
          document.getElementById(&#39;searchResult&#39;).innerHTML = &#39;出现错误:&#39; +data.msg;
        }
      }else{
        alert(&#39;发生错误:&#39; + xhr.status);
      }
    }
  }
  //发送请求
  var url = &#39;service.php&#39;;
  url = addURLParam(url,&#39;number&#39;,document.getElementById(&#39;keyword&#39;).value);
  xhr.open(&#39;get&#39;,url,true);
  xhr.send();
}
/*post*/
//创建
var oSave = document.getElementById(&#39;save&#39;);
//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&#39;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(&#39;Microsoft.XMLHTTP&#39;);
  }
  //异步接受响应
  xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
      if(xhr.status == 200){
        //实际操作
        var data = JSON.parse(xhr.responseText);
        if(data.success){
         document.getElementById(&#39;createResult&#39;).innerHTML = data.msg; 
       }else{
         document.getElementById(&#39;createResult&#39;).innerHTML = &#39;出现错误:&#39;+data.msg;
       }
      }else{
        alert(&#39;发生错误:&#39; + xhr.status);
      }
    }
  }
  //发送请求
  xhr.open(&#39;post&#39;,&#39;service.php&#39;,true);
  xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
  xhr.send(serialize(document.getElementById(&#39;postForm&#39;)));
}
</script>
</body>
</html>
Copy after login
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"=>&#39;总经理&#39;),
  array("name"=>"郭靖","number"=>"102","sex"=>"男","job"=>&#39;开发工程师&#39;),
  array("name"=>"黄蓉","number"=>"103","sex"=>"女","job"=>&#39;产品经理&#39;)
  );
//判断如果是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[&#39;number&#39;]) || empty($_GET[&#39;number&#39;])){
    echo &#39;{"success":false,"msg":"参数错误"}&#39;;
    return;
  }
  global $staff;
  $number = test_input($_GET[&#39;number&#39;]);
  $result = &#39;{"success":false,"msg":"没有找到员工"}&#39;;
  //遍历$staff多维数组,查找key值为number的员工是否存在。如果存在,则修改返回结果
  foreach($staff as $value){
    if($value[&#39;number&#39;] == $number){
      $result = &#39;{"success":true,"msg":"找到员工:员工编号为&#39; .$value["number"] .&#39;,员工姓名为&#39; .$value["name"] .&#39;,员工性别为&#39; .$value["sex"] .&#39;,员工职位为&#39; .$value["job"] .&#39;"}&#39;;
      break;
    }
  }
  echo $result;
}
//创建员工
function create(){
  //判断信息是否填写完全
  if(!isset($_POST[&#39;name&#39;]) || empty($_POST[&#39;name&#39;]) || 
    !isset($_POST[&#39;number&#39;]) || empty($_POST[&#39;number&#39;]) ||
    !isset($_POST[&#39;sex&#39;]) || empty($_POST[&#39;sex&#39;]) ||
    !isset($_POST[&#39;job&#39;]) || empty($_POST[&#39;job&#39;]) 
    ){
    echo &#39;{"success":false,"msg":"参数错误,员工信息填写不全"}&#39;;
    return;
  }
  echo &#39;{"success":true,"msg":"员工&#39; .test_input($_POST[&#39;name&#39;]) .&#39;信息保存成功!"}&#39;;
}
?>
Copy after login

Example demonstration

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Characteristics of Ajax and garbled code problems (graphic tutorial)

formData image and data upload based on Ajax

Ajax asynchronous request technology example explanation

The above is the detailed content of Ajax passes JSON example 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)

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

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.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

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-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese In-depth understanding of PHP: Implementation method of converting JSON Unicode to Chinese Mar 05, 2024 pm 02:48 PM

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Quick tips for converting PHP arrays to JSON Quick tips for converting PHP arrays to JSON May 03, 2024 pm 06:33 PM

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.

How to use PHP functions to process JSON data? How to use PHP functions to process JSON data? May 04, 2024 pm 03:21 PM

PHP provides the following functions to process JSON data: Parse JSON data: Use json_decode() to convert a JSON string into a PHP array. Create JSON data: Use json_encode() to convert a PHP array or object into a JSON string. Get specific values ​​of JSON data: Use PHP array functions to access specific values, such as key-value pairs or array elements.

See all articles