Home Web Front-end JS Tutorial js combined with json to implement ajax simple case_AJAX related

js combined with json to implement ajax simple case_AJAX related

Jun 28, 2017 pm 01:59 PM
ajax javascript json

This article mainly introduces the relevant information of js combined with json to implement ajax simple example in detail. It has certain reference value. Interested friends can refer to it

Preliminary 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 the WWW directory in PHPstudy, and the index page runs by default
3. bootstrap.css

Interface screenshot:

##phpstudy is very convenient to use. If you have not installed php on your computer, you must First configure the system environment variables, add the path to php.exe (find it in the PHPstudy installation directory), and then enter php -v in cmd. If the installation version of php and other information appear, it means the installation is successful.


#Then create a new project in the WWW folder of PHPstudy, here I named it AjaxDemo.


index.html

<!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>
Copy after login

staffManage.js

Ajax instantiation can be divided into five points, which is easier to remember:


1. New an XMLHttpRequest instance
Note that it is compatible with lower versions of IE browser

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, and the second parameter specifies URL address, the third parameter specifies whether to use asynchronous, the default is true, so there is no need to write it.

3*If you make a post request, you must also add the request header setRequestHeader ("Content-Type", "application/x-www-form-urlencoded")


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(&#39;keyword&#39;),     //员工编号
      oSearchBtn=document.getElementById(&#39;search&#39;),     //查询按钮
      oSearchRes=document.getElementById(&#39;searchResult&#39;); //反馈结果显示

    // 查询员工按钮点击事件  
    oSearchBtn.onclick=function(){
      searchStaff();
    }
    // 创建查询员工方法
    function searchStaff(){
      //var xhr=new XMLHttpRequest();
      //标准写法和IE写法混在一起,可以兼容低版本的IE浏览器
      var xhr;
      if (window.XMLHttpRequest) {
        xhr= new XMLHttpRequest();
      } else {
        xhr= new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;);
      }

      xhr.open(&#39;GET&#39;,&#39;serverjson.php?number=&#39;+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(&#39;(&#39;+xhr.responseText+&#39;)&#39;)
            oSearchRes.innerHTML=data.msg;
          }
        }
      }
    }

    // 增加员工    
    var oAddnumber=document.getElementById(&#39;add-number&#39;), //员工编号
      oAddname=document.getElementById(&#39;add-name&#39;), //员工姓名
      oAddsex=document.getElementById(&#39;add-sex&#39;), //员工性别
      oAddjob=document.getElementById(&#39;add-job&#39;), //员工职位
      oAddSearch=document.getElementById(&#39;add-search&#39;), //增加员工按钮
      oAddResult=document.getElementById(&#39;add-resultshow&#39;); //反馈结果显示

    // 增加员工按钮点击事件
    oAddSearch.onclick=function(){
      createStaff();
    }
    // 创建增加员工方法
    function createStaff(){

      var xhr;
      if(xhr.XMLHttpRequest){
        xhr = new XMLHttpRequest();
      }else{
        xhr = new ActiveXObject(&#39;Microsoft.XMLHTTP&#39;);
      }

      xhr.open(&#39;POST&#39;,&#39;serverjson.php&#39;);

      //这里注意key=value的等于号两边不要出现空格,会出现错误
      var data=&#39;name=&#39;+oAddname.value
      +&#39;&number=&#39;+oAddnumber.value
      +&#39;&sex=&#39;+oAddsex.value
      +&#39;&job=&#39;+oAddjob.value;

      //在open和send之间设置Content-Type
      xhr.setRequestHeader(&#39;Content-Type&#39;,&#39;application/x-www-form-urlencoded&#39;);

      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=&#39;出现错误:&#39;+data.msg;
            }
          }else{
            alert(&#39;发生错误!&#39;+xhr.status)
          }
        }
      }
    }
Copy after login
serverjson.php
<?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 &#39;{"success":false,"msg":"参数错误"}&#39;;
    return;
  }
  //函数之外声明的变量拥有 Global 作用域,只能在函数以外进行访问。
  //global 关键词用于访问函数内的全局变量
  global $staff;
  //获取number参数
  $number = $_GET["number"];
  $result = &#39;{"success":false,"msg":"没有找到员工。"}&#39;;

  //遍历$staff多维数组,查找key值为number的员工是否存在,如果存在,则修改返回结果
  foreach ($staff as $value) {
    if ($value["number"] == $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["name"]) || empty($_POST["name"])
    || !isset($_POST["number"]) || empty($_POST["number"])
    || !isset($_POST["sex"]) || empty($_POST["sex"])
    || !isset($_POST["job"]) || empty($_POST["job"])) {
    echo &#39;{"success":false,"msg":"参数错误,员工信息填写不全"}&#39;;
    return;
  }
  //TODO: 获取POST表单数据并保存到数据库

  //提示保存成功
  echo &#39;{"success":true,"msg":"员工:&#39; . $_POST["name"] . &#39; 信息保存成功!"}&#39;;
}

?>
Copy after login


Summary

The whole process is roughly as shown in the figure:


The above is the detailed content of js combined with json to implement ajax simple case_AJAX related. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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.

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

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:

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

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.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

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.

See all articles