国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 PHP開發(fā) 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:

//創(chuàng)建ajax通信服務(wù)器對(duì)象
 
function getHTTPObject(){
 
  "use strict"; //注意使用嚴(yán)格模式
 
  var xhr;
 
  //使用主流的XMLHttpRequest通信服務(wù)器對(duì)象
 
  if(window.XMLHttpRequest){
 
    xhr = new window.XMLHttpRequest();
 
  //如果是老版本ie,則只支持Active對(duì)象
  } else if(window.ActiveXObject){
 
    xhr = new window.ActiveXObject("Msxml2.XMLHTTP");
  }
 
  //將通信服務(wù)器對(duì)象返回
  return xhr;
 
}

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"
    }
  ]
};

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調(diào)用所返回的json數(shù)據(jù)
 
var request = getHTTPObject();
 
request.onreadystatechange = function(){
 
  "use strict";
 
    //當(dāng)readyState全等于“4”狀態(tài),status全等于“200”狀態(tài) 代表服務(wù)器狀態(tài)服務(wù)及客戶端請(qǐng)求正常,得以返回
  if(request.readyState ===4 || request.status ===200 ){
     
    //為了方便起見,將數(shù)據(jù)打印到瀏覽器控制臺(tái)(F12查看)
    console.log(request.responseText);
  }
   
  //使用GET方式請(qǐng)求.json數(shù)據(jù)文件,并且不向服務(wù)器發(fā)送任何信息
  request.open("GET","data/ingredient.json",true);
  request.send(null);
};

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:

//將其封裝成一個(gè)供調(diào)用函數(shù)
 
function ajaxCall(dataUrl,outputElement,callback){
  "use strict";  //這是一段截取的js(ajax)代碼
 
  var request = getHTTPObject();
  //我想要提醒大家的是:當(dāng)網(wǎng)頁的某個(gè)區(qū)域在向服務(wù)器發(fā)送http請(qǐng)求的過程中,要有一個(gè)標(biāo)識(shí)提醒用戶正在加載...
 
  outputElement.innerHTML = "Loding..."; //也可以根據(jù)各位的需求添加一個(gè)循環(huán)小動(dòng)畫
 
  request.onreadystatechange = function () {
 
    if(request.readyState ===4 || request.status ===200){
 
      //將request.responseText返回的數(shù)據(jù)轉(zhuǎn)化成JSON格式
      var contacts = JSON.parse(request.responseText);
       
      //如果回調(diào)函數(shù)是function類型,則使用callback函數(shù)處理返回的JSON數(shù)據(jù)
      if(callback === "function"){
        callback(contacts);
      }
    }
  };
 
  request.open("GET","data/ingredient.json",true);
  request.send(null);
}

Then calls ajaxCall():

//調(diào)用程序,我們將使用Ajax請(qǐng)求的JSON數(shù)據(jù)顯示到HTML文檔的某個(gè)區(qū)域中!
(function () {
  "use strict";
 
    //下面將給出DOM語句相對(duì)應(yīng)的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");
        //請(qǐng)求的JSON數(shù)據(jù)文件名,輸出到HTML的區(qū)域,檢索數(shù)據(jù)文件的核心function語句
 
      ajaxCall('data/ingredient.json','output',function(data){
 
        //searchValue為搜索條目,準(zhǔn)備循環(huán)檢索
        var searchValue = searchField.value,
 
          //找到食材條目(詳見JSON數(shù)據(jù)文件)
          fruit = data.fruit,
 
          //統(tǒng)計(jì)水果的數(shù)量
          count = fruit.length,
          i;
 
        //阻止默認(rèn)行為
        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中匹配的數(shù)據(jù)規(guī)范的寫入到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;
            }
          }
        }
      })
    }
  };
  //事件監(jiān)聽器,監(jiān)聽鼠標(biāo)單擊事件后調(diào)用函數(shù)并請(qǐng)求JSON數(shù)據(jù)文件
  searchField.addEventListener("click",search.salad,false);
   
})();

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>


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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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)

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 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 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 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

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.

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 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