search
HomeWeb Front-endJS TutorialDetailed explanation of the use of three ajax parsing modes

This time I will bring you a detailed explanation of the use of the three ajax parsing modes. What are the precautions when using the three ajax parsing modes. The following is a practical case, let's take a look.

1. JSON format in Ajax

html code:


 <input>
 <script>
  var btn = document.getElementById("btn");
  btn.onclick = function(){
    var xhr = getXhr();
    xhr.open("post","10.php");
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    /*
     * 在客户端如何构建JSON格式
     * * 构建符合JSON格式的字符串
     */
    var user = &#39;{"name":"zhangwuji","pwd":"123456"}&#39;;
    xhr.send("user="+user);
    xhr.onreadystatechange = function(){
      if(xhr.readyState==4&&xhr.status==200){
        var data = xhr.responseText;
        /*
         * 使用eval()函数进行转换
         * * 使用"()"将其包裹,eval()函数强制将其转换为JSON格式(javascript代码)
         * * 不使用"()"将其包裹,eval()函数将其识别为一个空的代码块
         */
        var json = eval("("+data+")");
        console.log(json);
      }
    }
  }
  function getXhr(){
    var xhr = null;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject("Microsoft.XMLHttp");
    }
    return xhr;
  }
 </script>
 

PHP code

<?php   // 接收客户端发送的请求数据
  $user = $_POST[&#39;user&#39;];
  // 就是一个JSON格式的string字符串
  //var_dump($user);
  $json_user = json_decode($user,true);
  //var_dump($json_user[&#39;name&#39;]);
  $json = &#39;{"a":1,"b":2,"c":3,"d":4,"e":5}&#39;;
  //var_dump(json_decode($json));
  // 响应数据符合JSON格式的字符串
  // 1. 手工方式构建
  //echo &#39;{"name":"zhouzhiruo","pwd":"123456"}&#39;;
  // 2. 使用json_encode()函数
  echo json_encode($json_user);
?>

二 XML format in Ajax

html page:

   
 <input>
 <script>
  var btn = document.getElementById("btn");
  btn.onclick = function(){
    // 实现Ajax的异步交互
    var xhr = getXhr();
    xhr.open("post","07.php");
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    /*
     * 如何构建符合XML格式的请求数据
     * * 注意
     *  * 请求数据的格式 - key=value 不能改变的
     * * 将value值构建成符合XML格式的数据
     *  * 数据类型 - 字符串(string)
     *  * 格式符合XML的语法要求
     * * 编写注意
     *  * 定义变量 - 专门构建XML格式的数据
     *  * 在send()方法进行拼串
     */
    var user = "<user><name>zhangwuji<pwd>123456";
    xhr.send("user="+user);
    xhr.onreadystatechange = function(){
      if(xhr.readyState==4&&xhr.status==200){
        // 接收服务器端的响应数据
        var xmlDoc = xhr.responseXML;
        var nameEle = xmlDoc.getElementsByTagName("name")[0];
        var txtEle = nameEle.childNodes[0];
        console.log(txtEle.nodeValue);
      }
    }
  }
  function getXhr(){
    var xhr = null;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject("Microsoft.XMLHttp");
    }
    return xhr;
  }
 </script>
 

PHP page code:

<?php   // 接收客户端发送的请求数据
  $user = $_POST[&#39;user&#39;];//符合XML格式要求的string类型
  //var_dump($user);
  // 创建DOMDocument对象
  $doc = new DOMDocument();
  // 调用loadXML()方法
  $result = $doc->loadXML($user);
  //var_dump($doc);
  // 如何构建符合XML格式的数据
  /* 修改响应头的Content-Type值为"text/xml"
  header('Content-Type:text/xml');
  echo $user;// 符合XML格式的string类型
  */
  header('Content-Type:application/xml');
  echo $doc->saveXML();
?>

三 HTML format in Ajax

HTML page:

  
 <select>
  <option>请选择</option>
  <option>山东省</option>
  <option>辽宁省</option>
  <option>吉林省</option>
 </select>
 <select>
  <option>请选择</option>
 </select>
 <script>
  /*
   * 需要思考哪些事情?
   * * 在什么时候执行Ajax的异步请求?
   *  * 当用户选择具体的省份信息时
   */
  // 1. 为id为province元素绑定onchange事件
  var provinceEle = document.getElementById("province");
  provinceEle.onchange = function(){
    // 清空
    var city = document.getElementById("city");
    var opts = city.getElementsByTagName("option");
    for(var z=opts.length-1;z>0;z--){
      city.removeChild(opts[z]);
    }
    if(provinceEle.value != "请选择"){
      // 2. 执行Ajax异步请求
      var xhr = getXhr();
      xhr.open("post","06.php");
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
      xhr.send("provcince="+provinceEle.value);
      xhr.onreadystatechange = function(){
        if(xhr.readyState==4&&xhr.status==200){
          // 接收服务器端的数据内容
          var data = xhr.responseText;
          // data是字符串,转换为数组
          var cities = data.split(",");
          for(var i=0;i<cities.length;i++){
            var option = document.createElement("option");
            var textNode = document.createTextNode(cities[i]);
            option.appendChild(textNode);
            city.appendChild(option);
          }
        }
      }
    }
  }
  // 定义创建XMLHttpRequest对象的函数
  function getXhr(){
    var xhr = null;
    if(window.XMLHttpRequest){
      xhr = new XMLHttpRequest();
    }else{
      xhr = new ActiveXObject("Microsoft.XMLHttp");
    }
    return xhr;
  }
 </script>
 

php page:

<?php   // 用于处理客户端请求二级联动的数据
  // 1. 接收客户端发送的省份信息
  $province = $_POST[&#39;provcince&#39;];
  // 2. 判断当前的省份信息,提供不同的城市信息
  switch ($province){
    case &#39;山东省&#39;:
      echo &#39;青岛市,济南市,威海市,日照市,德州市&#39;;
      break;
    case &#39;辽宁省&#39;:
      echo &#39;沈阳市,大连市,铁岭市,丹东市,锦州市&#39;;
      break;
    case &#39;吉林省&#39;:
      echo &#39;长春市,松原市,吉林市,通化市,四平市&#39;;
      break;
  }
  // 服务器端响应的是字符串
?>

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of Ajax and $.ajax instances

Adjustment of ajax execution order in jquery

Ajax implements loading waiting effect to improve user experience

The above is the detailed content of Detailed explanation of the use of three ajax parsing modes. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Scrapy基于Ajax异步加载实现方法Scrapy基于Ajax异步加载实现方法Jun 22, 2023 pm 11:09 PM

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

如何使用CakePHP中的AJAX?如何使用CakePHP中的AJAX?Jun 04, 2023 pm 08:01 PM

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

jquery ajax报错403怎么办jquery ajax报错403怎么办Nov 30, 2022 am 10:09 AM

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

ajax传递中文乱码怎么办ajax传递中文乱码怎么办Nov 15, 2023 am 10:42 AM

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

Nginx中404页面怎么配置及AJAX请求返回404页面Nginx中404页面怎么配置及AJAX请求返回404页面May 26, 2023 pm 09:47 PM

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

什么是ajax重构什么是ajax重构Jul 01, 2022 pm 05:12 PM

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

在Laravel中如何通过Ajax请求传递CSRF令牌?在Laravel中如何通过Ajax请求传递CSRF令牌?Sep 10, 2023 pm 03:09 PM

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C

使用HTML5文件上传与AJAX和jQuery使用HTML5文件上传与AJAX和jQuerySep 13, 2023 am 10:09 AM

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById(&#39;fileBox&#39;).files[0];varreader=newFileReader();reader.readAsText(file,&#39;UTF-8&#39;);reader.onload=myFunc;functionmyFunc(event){&nbsp;&nbsp;varres

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version