Home  >  Article  >  Web Front-end  >  Let’s briefly talk about how to use ajax to interact

Let’s briefly talk about how to use ajax to interact

WBOY
WBOYforward
2022-02-08 17:52:542459browse

This article brings you relevant knowledge about ajax interaction, including synchronous and asynchronous, callback functions, the use of promises and other related issues. I hope it will be helpful to everyone.

Let’s briefly talk about how to use ajax to interact

Synchronous and asynchronous

Synchronous: It means that things must be done one by one. You can do the next task only after completing the previous one

Asynchronous: Not affected by the current task, two things are done at the same time. When doing one thing, it does not affect the progress of the other thing.

In programming: When asynchronous program code is executed, it will not block the execution of other program codes, thus improving the overall execution efficiency.

Let’s briefly talk about how to use ajax to interact

The concept of ajax

What is ajax

1 Ajax: asynchronous javascript and xml (asynchronous js and xml)

2 is one of the technologies that can interact (asynchronously/synchronously) with the server.

ajax的语言载体是javascript。 最大特点:页面不刷新
ajax的一些常见应用,使网页无刷新向web服务器发送请求数据.

Let’s briefly talk about how to use ajax to interact

Let’s briefly talk about how to use ajax to interact

The history of the emergence of ajax

In 1999, when Microsoft released the IE5 browser, it was embedded technology. The original name was XMLHttp
Until 2005, Google released an email product gmail, which used ajax technology internally. This incident attracted people's attention to ajax, and also caused the languishing javascript language to be taken seriously from now on

Usage of ajax

XMLHttpRequest object

The browser's built-in object is used to communicate with the server (exchange data), so that we can partially update the web page instead of refreshing it entire page. This request is asynchronous, that is, when sending the request to the server, it will not hinder the running of the program, and the browser will continue to render subsequent structures.

Ajax operation

Be sure to open phpsudy, and the js file and php file are on the same host before the request can be successful.

Creation of GET request

Creation and sending of request

Creation of mainstream browsers (Firefox, Google, Apple Safari, Opera, including IE8 and above) The method is also the main one used now.

//1. 创建一个XMLHttpRequest对象var xhr = new XMLHttpRequest();
//2. 设置请求的类型,以及地址
// 第一个参数:请求方式  get/post
// 第二个参数:请求的地址 需要在url后面拼上参数列表
// 第三个参数:默认是异步xhr.open("get", "01.php?name=Jepson",异步/同步);
//3.发送请求到服务器xhr.send(null);

Manual location

http://www.w3school.com.cn/ajax/ajax_xmlhttprequest_create.asp

USE OF GET

Example 1: Add a button to the page, click once to send a request to the php background, and php will write a piece of text into a.txt

    <input>
    <script>
    function fn(){
            // 1 实例化对象
            let xhr = new XMLHttpRequest();
        // 2 设置请求的类型以及地址
        xhr.open(&#39;get&#39;,&#39;./02.php&#39;);
        // 3 发送请求,get请求则设置为空,post请求则设置参数
        xhr.send();
    }

    </script>

The php code is as follows

<?php $str  = &#39;越懒散,越懒!&#39;;$file = &#39;./a.txt&#39;;$f = fopen($file,&#39;a&#39;);
  fwrite($f,$str);?>
ajax status

By monitoring the request status, data can be accepted only when the status is equal to 4

xhrObj.onreadystatechange - Monitor the readyState status, and when the status changes, the corresponding function can be called for processing

The role of the five ajax states

/*xhrObj.readyState - Returns the status of the current request
When xhr.readyState = 0 - not initialized, the object has been established, and open() has not been called yet
xhr .readyState = 1 time - initialization, object creation did not call send()
xhr.readyState = 2 time - sending data, send() method call, but the current status and http header are unknown, the request is not completed
xhr .readyState = 3 o'clock - data transmission, accepting part of the data
xhr.readyState = 4 o'clock - response content parsing completed
*/

Example: Obtain the four states of the ajax request process

    // 1 实例化对象
  let xhr = new XMLHttpRequest(); 
     xhr.onreadystatechange = function(){
          // 4 使用回调函数检测当前的状态
                console.log(xhr.readyState);
                // 获取服务器状态码
                console.log(xhr.status)
                // 接受服务器返回数据
               console.log(xhr.responseText);  
     }
    //  2 创建请求
     xhr.open('get','http://localhost/web/index.php');
     // 3 发送请求
     xhr.send();

Let’s briefly talk about how to use ajax to interact

Return server status code xhr.status

1**: Request received, continue processing
2**: Operation successfully received, analysis , Accept
3**: Completion of this request must require further processing
4**: The request contains an incorrect syntax or cannot be completed
5**: The server failed to execute a fully valid request

100——客户必须继续发出请求
101——客户要求服务器根据请求转换HTTP协议版本

200——客户端请求成功
201——提示知道新文件的URL     
202——接受和处理、但处理未完成
203——返回信息不确定或不完整
204——请求收到,但返回信息为空
205——服务器完成了请求,用户代理必须复位当前已经浏览过的文件
206——服务器已经完成了部分用户的GET请求

300——请求的资源可在多处得到
301——删除请求数据
302——在其他地址发现了请求数据
303——建议客户访问其他URL或访问方式
304——客户端已经执行了GET,但文件未变化
305——请求的资源必须从服务器指定的地址得到
306——前一版本HTTP中使用的代码,现行版本中不再使用
307——申明请求的资源临时性删除

400——错误请求,如语法错误
401——请求授权失败
402——保留有效ChargeTo头响应
403——请求不允许
404——没有发现文件、查询或URl
405——用户在Request-Line字段定义的方法不允许
406——根据用户发送的Accept拖,请求资源不可访问
407——类似401,用户必须首先在代理服务器上得到授权
408——客户端没有在用户指定的饿时间内完成请求
409——对当前资源状态,请求不能完成
410——服务器上不再有此资源且无进一步的参考地址
411——服务器拒绝用户定义的Content-Length属性请求
412——一个或多个请求头字段在当前请求中错误
413——请求的资源大于服务器允许的大小
414——请求的资源URL长于服务器允许的长度
415——请求资源不支持请求项目格式
416——请求中包含Range请求头字段,在当前请求资源范围内没有range指示值,请求也不包含If-Range请求头字段
417——服务器不满足请求Expect头字段指定的期望值,如果是代理服务器,可能是下一级服务器不能满足请求

500——服务器产生内部错误
501——服务器不支持请求的函数
502——服务器暂时不可用,有时是为了防止发生系统过载
503——服务器过载或暂停维修
504——关口过载,服务器使用另一个关口或服务来响应用户,等待时间设定值较长
505——服务器不支持或拒绝支请求头中指定的HTTP版本
Server response value reception

To obtain the response from the server, use the responseText or responseXML attribute of the XMLHttpRequest object.

##responseGet the characters Response data in string form. responseXMLGet response data in XML form (know).

接受服务器返回值

nbsp;html>
    
        <meta>
    
    <script>
      function f1(){
        //创建ajax对象
        var xhr  = new XMLHttpRequest();
        //设置请求的地址
        xhr.open(&#39;get&#39;,&#39;./reponse.php&#39;);
        //发送请求,如果是get请求则参数设置为null
        xhr.send();
        //显示ajax的状态
        /*
        ajax的四中状态
        0 对象已创建,请求连接未初始化(尚未调用open方法)
        1 请求连接已经已经建立没有调用send方法
        2 请求连接已建立,调用send方法
        3 数据已经开始传输但尚未完成
        4 数据传输已经完成,请求已经完成
         */
           // onreadystatechange 当请求的状态发生改变时,就会触发
        xhr.onreadystatechange=function(){
            //显示五种状态
            //console.log(xhr.readyState);
            //判断当的请求状态等于4时,代表数据传输完成
             if(xhr.readyState==4 && xhr.status==200){
                //使用responseText接受服务器端传递的数据
                //alert(xhr.responseText);
                //追加显示到页面中
               document.body.innerHTML+=xhr.responseText;
             }
        }
        
        //alert(xhr.responseText);
      }
    </script>
    
    <input>
    

服务器代码

<?php $a = &#39;1234&#39;;echo $a;?>

总结:

1 创建对象let xhr = new XMLHttpRequest();2 设置请求

xhr.open(get,请求地址)3 发送请求

xhr.send()4 判断状态接收返回值

xhr.onreadystatechange = funtion(){

   if(xhr.readyState==4 && xhr.status==200){// 接受返回值let str = xhr.response  }}

get和post的区别

1 get是地址栏的方式访问的,是可见的

2 get方式传递数据量比较小.安全性低.

3 post以非地址栏的形式访问,能够安全且大量的穿递数据

常见post使用

表单中使用, ajax中使用

POST方式

请求步骤
  1. 创建Ajax对象。

  2. 设置回调函数。接收后台返回的结果

  3. 设置请求

  4. 设置请求头信息“Content-type,application/x-www-form-urlencoded”

  5. 发送请求。

实现请求

setRequestHeader() 设置请求头信息

application/x-www-form-urlencoded 设置传递参数时,使用的编码格式(默认)

例:以post的方式传递数据

nbsp;html>
    
        <meta>
    
    <script>
     function f1(){
        //实例化ajax对象
        var xhr = new XMLHttpRequest();
        //设置请求的参数,设置以post方式发送请求
        xhr.open(&#39;post&#39;,&#39;./post.php&#39;);
         //如果需要像 HTML 表单那样 POST 数据,以&形式传输数据
        xhr.setRequestHeader(&#39;content-type&#39;, &#39;application/x-www-form-urlencoded&#39;);
        //构造传递的参数,形式与get传参的方式一致
        var data = &#39;name=张三&age=19&#39;;
         //发送请求
         xhr.send(data);

         //接受返回的信息
         xhr.onreadystatechange=function(){
            //验证当前的装态接受返回的信息
            if(xhr.readyState==4){
                //接受服务器返回的信
                var info = xhr.responseText;
                alert(info);
            }
         }
     }
    </script>
    
    <input>
    

同步和异步请求

异步:不等待ajax请求响应完毕,直接执行下面的代码

同步:等待ajax请求响应完毕后,再执行下面的代码

ajax的异步

异步示意图

Let’s briefly talk about how to use ajax to interact

ajax的同步

同步请求

Let’s briefly talk about how to use ajax to interact

验证同步与异步

js代码

    <input>
    <script>
    function fn(){
         // 1 实例化对象
         let xhr = new XMLHttpRequest();
         // 获取ajax的四种状态
         xhr.onreadystatechange = function(state){
             // console.log(xhr.readyState);
              //alert(xhr.responseText)
              if(xhr.readyState==4){
                  console.log(xhr.response)
              }
         }

        // 2 设置请求的类型以及地址,第三个参数设置为false,表示同步,设置为true表示异步(默认)
        xhr.open(&#39;get&#39;,&#39;http://localhost/demo.php&#39;,false);
        // 3 发送请求,get请求则设置为空,post请求则设置参数
        xhr.send();
        // 验证同步必须写的
        console.log(11111);
    }

 //   console.log(eval(&#39;{}&#39;));
 //   console.log(eval(&#39;({})&#39;));

    </script>

PHP代码

<?php $str  = &#39;越懒散,越懒!&#39;;$file = &#39;./a.txt&#39;;$f = fopen($file,&#39;a&#39;);
  fwrite($f,$str);
  // 让代码沉睡十秒之后,再向下执行
 sleep(10);
  echo &#39;这是输出的内容&#39;;?>

测试同步请求时,获取返回结果的responseText一定要放在send()之前

服务返回数据格式处理

类型

Text(又称HTML格式)

XML格式

JSON格式

Text类型处理

<script>
      var xhr = new XMLHttpRequest();
           xhr.onreadystatechange = function(){
            if(xhr.readyState==4){
                //接受返回的消息
                var info =xhr.responseText; 
               alert(info);
            }
           }
      xhr.open(&#39;get&#39;,&#39;./geshi.php&#39;);
      xhr.send(null);
    </script>[php代码]echo '<h2>完了,就要完了!</h2>';

json数据的处理

使用JOSN.parse()将PHP输出的json字符串转化为对象

<script>
      var xhr = new XMLHttpRequest();
           xhr.onreadystatechange = function(){
            if(xhr.readyState==4){
                //接受返回的消息,
                var info =xhr.responseText; 
                //将json数组转化为js对象
                 var str = JSON.parse(info);
                 console.log(str);
            }
           }
      xhr.open(&#39;get&#39;,&#39;./geshi.php&#39;);
      xhr.send(null);</script>[PHP代码]echo json_encode(array("name"=>'张三',"age"=>'12'));

xml数据的处理

 <script>
      var xhr = new XMLHttpRequest();
           xhr.onreadystatechange = function(){
            if(xhr.readyState==4){
                //接受返回的消息,使用responseXML接受
                var info =xhr.responseXML; 
                 var msg=info.getElementsByTagName(&#39;msg&#39;)[0].innerHTML;
                 console.log(msg);
            }
           }
      xhr.open(&#39;get&#39;,&#39;./geshi.php&#39;);
      xhr.send(null);</script>[PHP代码]<?phpheader (&#39;content-type:text/xml;charset=utf-8&#39;);echo &#39;<?xml version="1.0" encoding="utf-8" ?>
      <response>
      <status>1</status>
      <msg>返回的的消息</msg>
       </response>';

回调函数的嵌套

概念

回调函数是一个作为变量传递给另外一个函数的函数,它在主体函数执行完之后执行。

正常的代码都是链式操作,某一步执行出问题,则向下停止,而回调则不然.

常见的典型异步回调

    setTimeout(function(){
        console.log('1s之后做的事情');
        setTimeout(function(){
            console.log('2s之后做的事情');
            setTimeout(function(){
               console.log('3s之后做的事情');
            },1000);
        },1000);
    },1000);

在回调函数中嵌套,就是上一个函数执行完成,再执行下一个

promise使用

在JavaScript的世界中,所有代码都是单线程执行的。由于这个“缺陷”,导致JavaScript的所有网络操作,浏览器事件,都必须是异步执行。异步执行可以用回调函数实现.

Promise使ES6中引入的一个异步编程解决方案,与传统的ES5方法相比它的结构更合理,功能更强大.

特点

Promise对象代表一个异步操作,有三种状态:pending(进行中)、fulfilled(已成功)和rejected(已失败)。只有异步操作的结果,可以决定当前是哪一种状态,任何其他操作都无法改变这个状态.

语法:

  var p = new Promise(function(resolve,reject){})
 resolve 代表 决定(成功); reject 代表 失败

使用

基本使用

const p  = new Promise(function(resolve,reject){
    setTimeout(function(){
       // resolve('我是成功的')
       reject('这是失败的');
    },2000)
});

.then(callback)的使用(成功时调用)

.catch(callback的用法(失败时调用)

  p.then(function(data){
			console.log('resolved成功回调');
			console.log('成功回调接受的值:',data);
		}).catch(function(reason, data){
		    console.log('catch到rejected失败回调');
		     console.log('catch失败执行回调抛出失败原因:',reason);
	});	效果和写在then的第二个参数里面一样。它将大于10的情况下的失败回调的原因输出

注意:resolve和reject的两种状态

resolve作用是,将Promise对象的状态从“未完成”变为“成功”(即从 pending 变为 resolved),在异步操作成功时调用,并将异步操作的结果,作为参数传递出去;

reject作用是,将Promise对象的状态从“未完成”变为“失败”(即从 pending 变为 rejected),在异步操作失败时调用,并将异步操作报出的错误,作为参数传递出去。

promise改造ajax依赖调用

使用promise检测ajax的请求状态,利用promise的成功状态函数,返回ajax请求到的数据

第一步,将ajax进行封装

    const ajaxParam=param=>{
        return new Promise(function(resolve,reject){
            let xhr = new XMLHttpRequest();
        
              xhr.open('get',param.url); // 默认是true,表示异步
      
              xhr.send();
              xhr.onreadystatechange = function(){
                  if(xhr.readyState==4 ){
                      if(xhr.status==200){
                          resolve(xhr.responseText)
                      }else{
                          reject(xhr.responseText)
                      }

                  }
              }
        });

    }

第二步:使用then和catch获取结果,

      ajaxPromise({type:'get',url:'http//:www.baidu.com',data:null}).then(function(data){
          
      }).catch(function(data){
          
      });

扩展:

Promise.all()

所有的异步请求完成才执行的方法.

Promse.all在处理多个异步处理时非常有用,比如说一个页面上需要等两个或多个ajax的数据回来以后才正常显示,在此之前只显示loading图标。

let wake = (time) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve(`${time / 1000}秒后醒来`)
    }, time)
  })}let p1 = wake(3000);let p2 = wake(2000);Promise.all([p1, p2]).then((result) => {
  console.log(result)       // [ '3秒后醒来', '2秒后醒来' ]}).catch((error) => {
  console.log(error)})只有两次调用promise都执行完毕,才会执行all

Promise.race()

Promse.race就是赛跑的意思,意思就是说,Promise.race([p1, p2, p3])里面哪个结果获得的快,就返回那个结果,不管结果本身是成功状态还是失败状态。

let p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
  },1000)})let p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject('failed')
  }, 500)})Promise.race([p1, p2]).then((result) => {
  console.log(result)}).catch((error) => {
  console.log(error)  // 打开的是 'failed'})

【相关教程推荐:AJAX视频教程

Attributes Description

The above is the detailed content of Let’s briefly talk about how to use ajax to interact. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete