zoukankan      html  css  js  c++  java
  • 【原创】Ajax实现方式

    JQuery提供的Ajax方法:

     1 commonAjax: function (actionName, message) {
     2             var result;
     3             $.ajax({
     4                 async: false,
     5                 type: "post",
     6                 url: actionName,
     7                 dataType: "json",
     8                 timeout: 5000, // 设置请求超时时间(毫秒)。
     9                 contentType: "application/x-www-form-urlencoded; charset=utf-8",
    10                 data: {
    11                     message: message
    12                 },
    13                 success: function (data) {
    14                     // success(data);
    15                     result = data;
    16                 },
    17                 error: function (jqXHR, textStatus, errorThrown) {
    18                     if (textStatus == "timeout") {
    19                         result = "timeout";
    20                     }
    21                 }
    22             });
    23             return result;
    24         }

    $.ajax需要注意的一些地方:

      1.data主要方式有三种,html拼接的,json数组,form表单经serialize()序列化的;通过dataType指定,不指定智能判断。

      2.$.ajax只提交form以文本方式,如果异步提交包含<file>上传是传过不过去,需要使用jquery.form.js的$.ajaxSubmit

    原生js实现Ajax方法:

    var Ajax={
      get: function(url, fn) {
          // XMLHttpRequest对象用于在后台与服务器交换数据   
          var xhr = new XMLHttpRequest();            
          xhr.open('GET', url, true);
          xhr.onreadystatechange = function() {
            // readyState == 4说明请求已完成
            if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) { 
               // 从服务器获得数据 
               fn.call(this, xhr.responseText);  
            }
          };
          xhr.send();
      },
      // datat应为'a=a1&b=b1'这种字符串格式,在jq里如果data为对象会自动将对象转成这种字符串格式
      post: function (url, data, fn) {
          var xhr = new XMLHttpRequest();
          xhr.open("POST", url, true);
          // 添加http头,发送信息至服务器时内容编码类型
          xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
          xhr.onreadystatechange = function() {
             if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                 fn.call(this, xhr.responseText);
             }
          };
          xhr.send(data);
      }
    }

    注释:

    1. open(method, url, async) 方法需要三个参数:

      method:发送请求所使用的方法(GET或POST);

        与POST相比,GET更简单也更快,并且在大部分情况下都能用;

        然而,在以下情况中,请使用POST请求:

    • 无法使用缓存文件(更新服务器上的文件或数据库)
    • 向服务器发送大量数据(POST 没有数据量限制)
    • 发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠

      url:规定服务器端脚本的 URL(该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务));

      async:规定应当对请求进行异步(true)或同步(false)处理;true是在等待服务器响应时执行其他脚本,当响应就绪后对响应进行处理;false是等待服务器响应再执行。

    2. send() 方法可将请求送往服务器。

    3. onreadystatechange:存有处理服务器响应的函数,每当 readyState 改变时,onreadystatechange 函数就会被执行。

    4. readyState:存有服务器响应的状态信息。

    • 0: 请求未初始化(代理被创建,但尚未调用 open() 方法)
    • 1: 服务器连接已建立(open方法已经被调用)
    • 2: 请求已接收(send方法已经被调用,并且头部和状态已经可获得)
    • 3: 请求处理中(下载中,responseText 属性已经包含部分数据)
    • 4: 请求已完成,且响应已就绪(下载操作已完成)

    5. responseText:获得字符串形式的响应数据。

    6. setRequestHeader():POST传数据时,用来添加 HTTP 头,然后send(data),注意data格式;GET发送信息时直接加参数到url上就可以,比如url?a=a1&b=b1。

    PS:Fetch polyfill 的基本原理是探测是否存在window.fetch方法,如果没有则用 XHR 实现。

  • 相关阅读:
    nacos 命名空间
    Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences
    gitee
    maven引入junit 4.12,项目import org.junit.Test 还是报错.
    gitflow
    202011
    idea 忽略显示不需要的文件
    服务熔断 & 降级区别
    各种微服务框架对比
    zookeeper not connected
  • 原文地址:https://www.cnblogs.com/smallwangmusk/p/11391580.html
Copyright © 2011-2022 走看看