Home php教程 PHP开发 Ajax and server (JSON) communication example code

Ajax and server (JSON) communication example code

Dec 07, 2016 pm 03:33 PM
ajax

Ajax to Server (JSON) Communication

The word Ajax does not mean anything, it is just a term used to refer to a series of technologies that facilitate communication between client and server. Server communication is the core content of Ajax technology. Its goal is to send information from the client to the server and accept the return from the latter, in order to create a better user experience in the process. All server communication before Ajax was done on the server, so if you wanted to redraw part of the page, you either used an iframe (obsolete) or refreshed the entire page. Neither approach can be called a good user experience.

Ajax provides two types of server communication methods: synchronous communication and asynchronous communication.

Asynchronous communication Ajax is much more common than synchronous communication, with about 98% usage frequency. Asynchronous means that such Ajax calls are not triggered at the same time as other tasks. This communication behavior occurs in the background, is quite independent, and is separated from the page and web application.

Using asynchronous calls can avoid the blocking nature of synchronous calls, and it does not need to be processed together with other HTTP requests in the page.

XMLHttpRequest Object

The XMLHttpRequest object is the core of all Ajax calls. Our purpose is to use Ajax technology to asynchronously obtain the data in JSON and display it in an appropriate form:

//创建ajax通信服务器对象
 
function getHTTPObject(){
 
  "use strict"; //注意使用严格模式
 
  var xhr;
 
  //使用主流的XMLHttpRequest通信服务器对象
 
  if(window.XMLHttpRequest){
 
    xhr = new window.XMLHttpRequest();
 
  //如果是老版本ie,则只支持Active对象
  } else if(window.ActiveXObject){
 
    xhr = new window.ActiveXObject("Msxml2.XMLHTTP");
  }
 
  //将通信服务器对象返回
  return xhr;
 
}
Copy after login

Cross-browser compatibility issues: Microsoft Ie originally invented the XMLHttp object, which resulted in IE5 and IE6 only support ActiveXObject objects, so compatibility issues with them must be considered.

Create Ajax call

First, I created the Salad.json file in the local data directory and waited for the Ajax program to call it:

//ajax JSON Salad
var ingredient = {
  "fruit":[
    {
      "name" : "apple",
      "color" : "green"
    },
    {
      "name" : "tomato",
      "color" : "red"
    },
    {
      "name" : "peach",
      "color" : "pink"
    },
    {
      "name" : "pitaya",
      "color" : "white"
    },
    {
      "name" : "lettuce",
      "color" : "green"
    }
  ]
};
Copy after login

Then what I have to do is send a request to the server and accept the transfer Returned data:

After receiving the returned server communication object "xhr", what we need to do next is to use the readystatechange event to perform the Ajax request status and server status on the communication object "xhr". When the readystate status request is completed and status When the status server is normal, it will carry out subsequent communication work.

//输出ajax调用所返回的json数据
 
var request = getHTTPObject();
 
request.onreadystatechange = function(){
 
  "use strict";
 
    //当readyState全等于“4”状态,status全等于“200”状态 代表服务器状态服务及客户端请求正常,得以返回
  if(request.readyState ===4 || request.status ===200 ){
     
    //为了方便起见,将数据打印到浏览器控制台(F12查看)
    console.log(request.responseText);
  }
   
  //使用GET方式请求.json数据文件,并且不向服务器发送任何信息
  request.open("GET","data/ingredient.json",true);
  request.send(null);
};
Copy after login

Ajax is also called through the GET and POST methods. The GET method exposes the data in the URL, so it requires less processing work; POST is relatively safe, but its performance is not as good as GET. Next, use the open() and send() methods to request data files and send data to the server respectively.

Usually in actual development projects, it is impossible to have just one Ajax call. For reuse and convenience, we need to encapsulate this Ajax program into a reusable function. Here I pass in an outputElement parameter to prompt the user to wait; I also pass in a callback parameter to pass in a The callback function matches the keywords typed by the user in the search box in the JSON file and renders the appropriate data to the page response location:

//将其封装成一个供调用函数
 
function ajaxCall(dataUrl,outputElement,callback){
  "use strict";  //这是一段截取的js(ajax)代码
 
  var request = getHTTPObject();
  //我想要提醒大家的是:当网页的某个区域在向服务器发送http请求的过程中,要有一个标识提醒用户正在加载...
 
  outputElement.innerHTML = "Loding..."; //也可以根据各位的需求添加一个循环小动画
 
  request.onreadystatechange = function () {
 
    if(request.readyState ===4 || request.status ===200){
 
      //将request.responseText返回的数据转化成JSON格式
      var contacts = JSON.parse(request.responseText);
       
      //如果回调函数是function类型,则使用callback函数处理返回的JSON数据
      if(callback === "function"){
        callback(contacts);
      }
    }
  };
 
  request.open("GET","data/ingredient.json",true);
  request.send(null);
}
Copy after login

Then calls ajaxCall():

//调用程序,我们将使用Ajax请求的JSON数据显示到HTML文档的某个区域中!
(function () {
  "use strict";
 
    //下面将给出DOM语句相对应的HTML代码
  var searchForm = document.getElementById("search-form"),
    searchField = document.getElementById("q"),
    getAllButton = document.getElementById("get-all"),
    target = document.getElementById("output");
 
  var search = {
 
    salad : function(event){
 
      var output = document.getElementById("output");
        //请求的JSON数据文件名,输出到HTML的区域,检索数据文件的核心function语句
 
      ajaxCall('data/ingredient.json','output',function(data){
 
        //searchValue为搜索条目,准备循环检索
        var searchValue = searchField.value,
 
          //找到食材条目(详见JSON数据文件)
          fruit = data.fruit,
 
          //统计水果的数量
          count = fruit.length,
          i;
 
        //阻止默认行为
        event.preventDefault();
 
        //初始化
        target.innerHTML = "";
 
        if(count > 0 || searchValue !==""){
          for(i = 0;i < count;i++){
             
            var obj = fruit[i],
              //将name与searchvalue值相匹配,如果值不等于 -1,那么就确定两者相匹配
 
              inItfount = obj.name.indexOf(searchValue);
 
            //将JSON中匹配的数据规范的写入到DOM
            if(isItfount != -1){
              target.innerHTML += &#39;<p>&#39;+obj.name+&#39;<a href="mailto:" &#39;+obj.color+&#39;>&#39;+obj.color+&#39;</a></p>&#39;
            }
          }
        }
      })
    }
  };
  //事件监听器,监听鼠标单击事件后调用函数并请求JSON数据文件
  searchField.addEventListener("click",search.salad,false);
   
})();
Copy after login

HTML document corresponding to Ajax:

<h1>制作沙拉所需要的食材</h1>
 
  <form action="" method="get" id="search-form">
 
    <div class="section">
 
      <label for="q">搜索食材</label>
      <input id="q" name="q" required placeholder="type a name">
    </div>
 
 
    <div class="button-group">
 
      <button type="submit" id="btn-search">搜索</button>
      <button type="button" id="get-all">get all contacts</button>
 
    </div>
 
  </form>
 
  <div id="output"></div>
Copy after login


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)

Hot Topics

Java Tutorial
1658
14
PHP Tutorial
1257
29
C# Tutorial
1231
24
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 to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

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.

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.

What are the ajax versions? What are the ajax versions? Nov 22, 2023 pm 02:00 PM

Ajax is not a specific version, but a technology that uses a collection of technologies to asynchronously load and update web page content. Ajax does not have a specific version number, but there are some variations or extensions of ajax: 1. jQuery AJAX; 2. Axios; 3. Fetch API; 4. JSONP; 5. XMLHttpRequest Level 2; 6. WebSockets; 7. Server-Sent Events; 8, GraphQL, etc.

See all articles