整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:

在 JS 中如何使用 Ajax 来进行请求

人已经过原 Danny Markov 授权翻译

在本教程中,我们将学习如何使用 JS 进行AJAX调用。

1.AJAX

术语AJAX 表示 异步的 JavaScript 和 XML

AJAX 在 JS 中用于发出异步网络请求来获取资源。当然,不像名称所暗示的那样,资源并不局限于XML,还用于获取JSON、HTML或纯文本等资源。

有多种方法可以发出网络请求并从服务器获取数据。我们将一一介绍。

2.XMLHttpRequest

XMLHttpRequest对象(简称XHR)在较早的时候用于从服务器异步检索数据。

之所以使用XML,是因为它首先用于检索XML数据。现在,它也可以用来检索JSON, HTML或纯文本。

事例 2.1: GET

function success() {
  var data = JSON.parse(this.responseText)
  console.log(data)
}

function error (err) {
  console.log('Error Occurred:', err)
}

var xhr = new XMLHttpRequest()
xhr.onload = success
xhr.onerror = error
xhr.open("GET", ""https://jsonplaceholder.typicode.com/posts/1")
xhr.send()

我们看到,要发出一个简单的GET请求,需要两个侦听器来处理请求的成功和失败。我们还需要调用open()和send()方法。来自服务器的响应存储在responseText变量中,该变量使用JSON.parse()转换为JavaScript 对象。

function success() {
    var data = JSON.parse(this.responseText);
    console.log(data);
}

function error(err) {
    console.log('Error Occurred :', err);
}

var xhr = new XMLHttpRequest();
xhr.onload = success;
xhr.onerror = error;
xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.send(JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1
  })
);

我们看到POST请求类似于GET请求。我们需要另外使用setRequestHeader设置请求标头“Content-Type” ,并使用send方法中的JSON.stringify将JSON正文作为字符串发送。

2.3 XMLHttpRequest vs Fetch

早期的开发人员,已经使用了好多年的 XMLHttpRequest来请求数据了。现代的fetch API允许我们发出类似于XMLHttpRequest(XHR)的网络请求。主要区别在于fetch()API使用Promises,它使 API更简单,更简洁,避免了回调地狱。

3. Fetch API

Fetch 是一个用于进行AJAX调用的原生 JavaScript API,它得到了大多数浏览器的支持,现在得到了广泛的应用。

3.1 API用法

fetch(url, options)
    .then(response => {
        // handle response data
    })
    .catch(err => {
        // handle errors
    });

API参数

fetch() API有两个参数

  1. url是必填参数,它是您要获取的资源的路径。
  2. options是一个可选参数。不需要提供这个参数来发出简单的GET请求。
  • method: GET | POST | PUT | DELETE | PATCH
  • headers: 请求头,如 { “Content-type”: “application/json; charset=UTF-8” }
  • mode: cors | no-cors | same-origin | navigate
  • cache: default | reload | no-cache
  • body: 一般用于POST请求

API返回Promise对象

fetch() API返回一个promise对象。

  • 如果存在网络错误,则将拒绝,这会在.catch()块中处理。
  • 如果来自服务器的响应带有任何状态码(如200、404、500),则promise将被解析。响应对象可以在.then()块中处理。

错误处理

请注意,对于成功的响应,我们期望状态代码为200(正常状态),但是即使响应带有错误状态代码(例如404(未找到资源)和500(内部服务器错误)),fetch() API 的状态也是 resolved,我们需要在.then() 块中显式地处理那些。

我们可以在response 对象中看到HTTP状态:

  • HTTP状态码,例如200。
  • ok –布尔值,如果HTTP状态代码为200-299,则为true。

3.3 示例:GET

const getTodoItem = fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .catch(err => console.error(err));

getTodoItem.then(response => console.log(response));
Response

 { userId: 1, id: 1, title: "delectus aut autem", completed: false }

在上面的代码中需要注意两件事:

  1. fetch API返回一个promise对象,我们可以将其分配给变量并稍后执行。
  2. 我们还必须调用response.json()将响应对象转换为JSON

错误处理

我们来看看当HTTP GET请求抛出500错误时会发生什么:

fetch('http://httpstat.us/500') // this API throw 500 error
  .then(response => () => {
    console.log("Inside first then block");
    return response.json();
  })
  .then(json => console.log("Inside second then block", json))
  .catch(err => console.error("Inside catch block:", err));
Inside first then block
➤ ⓧ Inside catch block: SyntaxError: Unexpected token I in JSON at position 4

我们看到,即使API抛出500错误,它仍然会首先进入then()块,在该块中它无法解析错误JSON并抛出catch()块捕获的错误。

这意味着如果我们使用fetch()API,则需要像这样显式地处理此类错误:-

fetch('http://httpstat.us/500')
  .then(handleErrors)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(err => console.error("Inside catch block:", err));

function handleErrors(response) {
  if (!response.ok) { // throw error based on custom conditions on response
      throw Error(response.statusText);
  }
  return response;
}
 ➤ Inside catch block: Error: Internal Server Error at handleErrors (Script snippet %239:9)

3.3 示例:POST

fetch('https://jsonplaceholder.typicode.com/todos', {
    method: 'POST',
    body: JSON.stringify({
      completed: true,
      title: 'new todo item',
      userId: 1
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8"
    }
  })
  .then(response => response.json())
  .then(json => console.log(json))
  .catch(err => console.log(err))
Response

➤ {completed: true, title: "new todo item", userId: 1, id: 201}

在上面的代码中需要注意两件事:-

  1. POST请求类似于GET请求。我们还需要在fetch() API的第二个参数中发送method,body 和headers 属性。
  2. 我们必须需要使用 JSON.stringify() 将对象转成字符串请求body参数

4.Axios API

Axios API非常类似于fetch API,只是做了一些改进。我个人更喜欢使用Axios API而不是fetch() API,原因如下:

  • 为GET 请求提供 axios.get(),为 POST 请求提供 axios.post()等提供不同的方法,这样使我们的代码更简洁。
  • 将响应代码(例如404、500)视为可以在catch()块中处理的错误,因此我们无需显式处理这些错误。
  • 它提供了与IE11等旧浏览器的向后兼容性
  • 它将响应作为JSON对象返回,因此我们无需进行任何解析

4.1 示例:GET

// 在chrome控制台中引入脚本的方法

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/axios/dist/axios.min.js';
document.head.appendChild(script);
axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => console.log(response.data))
  .catch(err => console.error(err));
Response

{ userId: 1, id: 1, title: "delectus aut autem", completed: false }

我们可以看到,我们直接使用response获得响应数据。数据没有任何解析对象,不像fetch() API。

错误处理

axios.get('http://httpstat.us/500')
  .then(response => console.log(response.data))
  .catch(err => console.error("Inside catch block:", err));
Inside catch block: Error: Network Error

我们看到,500错误也被catch()块捕获,不像fetch() API,我们必须显式处理它们。

4.2 示例:POST

axios.post('https://jsonplaceholder.typicode.com/todos', {
      completed: true,
      title: 'new todo item',
      userId: 1
  })
  .then(response => console.log(response.data))
  .catch(err => console.log(err))
 {completed: true, title: "new todo item", userId: 1, id: 201}

我们看到POST方法非常简短,可以直接传递请求主体参数,这与fetch()API不同。


作者:Danny Markov 译者:前端小智 来源:tutorialzine

原文:https://tutorialzine.com/2017/12-terminal-commands-every-web-developer-should-know

法: $.ajax([settings]);


  1. $.ajax({
  2. type: "POST",
  3. url: "UserLogincheck",
  4. data: {username:$("#username").val(), password:$("#password").val(),verify:$("#verify").val()},
  5. dataType: "json",
  6. success: function(data){
  7. if(data==1){
  8. // 用户名或密码错误
  9. alert("用户名或密码错误");
  10. }
  11. else if(data==2){
  12. alert("验证码错误");
  13. // 验证码错误
  14. }
  15. else if(data==0){
  16. window.location.href="index";
  17. }
  18. //跳转页面
  19. },
  20. error:function(XMLHttpRequest, textStatus, errorThrown){//请求失败时调用此函数
  21. console.log(XMLHttpRequest.status);
  22. console.log(XMLHttpRequest.readyState);
  23. console.log(textStatus);
  24. }
  25. });

php作为后台的处理过程


  1. public function UserLogincheck(){//用户登陆验证(用户名和邮箱均可登陆)
  2. $very = new \Think\Verify();
  3. if($very->check($_POST['verify'])){//验证码正确
  4. $user_admin = I('post.username');
  5. $judge = " (user_name = '$user_admin' or user_email = '$user_admin' )";
  6. $user_del_status = $this->user->where($judge)->getField('user_del');
  7. if($user_del_status == 0){//用户未被注销
  8. $user_password = I('post.password');
  9. $judge .= "and user_password = '$user_password'";
  10. $res = $this->user->where($judge)->find();
  11. if($res){//记录用户登陆状态
  12. $_SESSION['ADMIN_user_id'] = $this->user->where($judge)->getField('user_id');
  13. $_SESSION['ADMIN_user_name'] = $data['user_name'];
  14. $this->ajaxReturn(0);//登陆成功
  15. }
  16. $this->ajaxReturn(1);//用户名或密码错误
  17. }
  18. else
  19. $this->ajaxReturn(8);//用户信息被注销
  20. }
  21. else
  22. $this->ajaxReturn(2);//验证码错误
  23. }

ajax参数详解:

data

类型:String

发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为 Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:["bar1", "bar2"]} 转换为 '&foo=bar1&foo=bar2'。

dataFilter

类型:Function

给 Ajax 返回的原始数据的进行预处理的函数。提供 data 和 type 两个参数:data 是 Ajax 返回的原始数据,type 是调用 jQuery.ajax 时提供的 dataType 参数。函数返回的值将由 jQuery 进一步处理。

dataType

类型:String

预期服务器返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断,比如 XML MIME 类型就被识别为 XML。在 1.4 中,JSON 就会生成一个 JavaScript 对象,而 script 则会执行这个脚本。随后服务器端返回的数据会根据这个值解析后,传递给回调函数。可用值:

"xml": 返回 XML 文档,可用 jQuery 处理。

"html": 返回纯文本 HTML 信息;包含的 script 标签会在插入 dom 时执行。

"script": 返回纯文本 JavaScript 代码。不会自动缓存结果。除非设置了 "cache" 参数。注意:在远程请求时(不在同一个域下),所有 POST 请求都将转为 GET 请求。(因为将使用 DOM 的 script标签来加载)

"json": 返回 JSON 数据 。

"jsonp": JSONP 格式。使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数。

"text": 返回纯文本字符串

error

类型:Function

默认值: 自动判断 (xml 或 html)。请求失败时调用此函数。

有以下三个参数:XMLHttpRequest 对象、错误信息、(可选)捕获的异常对象。

如果发生了错误,错误信息(第二个参数)除了得到 null 之外,还可能是 "timeout", "error", "notmodified" 和 "parsererror"。

这是一个 Ajax 事件。

global

类型:Boolean

是否触发全局 AJAX 事件。默认值: true。设置为 false 将不会触发全局 AJAX 事件,如 ajaxStart 或 ajaxStop 可用于控制不同的 Ajax 事件。

ifModified

类型:Boolean

仅在服务器数据改变时获取新数据。默认值: false。使用 HTTP 包 Last-Modified 头信息判断。在 jQuery 1.4 中,它也会检查服务器指定的 'etag' 来确定数据没有被修改过。

jsonp

类型:String

在一个 jsonp 请求中重写回调函数的名字。这个值用来替代在 "callback=?" 这种 GET 或 POST 请求中 URL 参数里的 "callback" 部分,比如 {jsonp:'onJsonPLoad'} 会导致将 "onJsonPLoad=?" 传给服务器。

jsonpCallback

类型:String

为 jsonp 请求指定一个回调函数名。这个值将用来取代 jQuery 自动生成的随机函数名。这主要用来让 jQuery 生成度独特的函数名,这样管理请求更容易,也能方便地提供回调函数和错误处理。你也可以在想让浏览器缓存 GET 请求的时候,指定这个回调函数名。

password

类型:String

用于响应 HTTP 访问认证请求的密码

processData

类型:Boolean

默认值: true。默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 "application/x-www-form-urlencoded"。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

scriptCharset

类型:String

只有当请求时 dataType 为 "jsonp" 或 "script",并且 type 是 "GET" 才会用于强制修改 charset。通常只在本地和远程的内容编码不同时使用。

success

类型:Function

请求成功后的回调函数。

参数:由服务器返回,并根据 dataType 参数进行处理后的数据;描述状态的字符串。

这是一个 Ajax 事件。

traditional

类型:Boolean

如果你想要用传统的方式来序列化数据,那么就设置为 true。请参考工具分类下面的 jQuery.param 方法。

timeout

类型:Number

设置请求超时时间(毫秒)。此设置将覆盖全局设置。

type

类型:String

默认值: "GET")。请求方式 ("POST" 或 "GET"), 默认为 "GET"。注意:其它 HTTP 请求方法,如 PUT 和 DELETE 也可以使用,但仅部分浏览器支持。

url

类型:String

默认值: 当前页地址。发送请求的地址。

username

类型:String

用于响应 HTTP 访问认证请求的用户名。

xhr

类型:Function

需要返回一个 XMLHttpRequest 对象。默认在 IE 下是 ActiveXObject 而其他情况下是 XMLHttpRequest 。用于重写或者提供一个增强的 XMLHttpRequest 对象。这个参数在 jQuery 1.3 以前不可用。

. ajax的介绍

ajax 是 Asynchronous JavaScript and XML的简写,ajax一个前后台配合的技术,它可以让 javascript 发送异步的 http 请求,与后台通信进行数据的获取,ajax 最大的优点是实现局部刷新,ajax可以发送http请求,当获取到后台数据的时候更新页面显示数据实现局部刷新,在这里大家只需要记住,当前端页面想和后台服务器进行数据交互就可以使用ajax了。

这里提示一下大家, 在html页面使用ajax需要在web服务器环境下运行, 一般向自己的web服务器发送ajax请求。

2. ajax的使用

jquery将它封装成了一个方法$.ajax(),我们可以直接用这个方法来执行ajax请求。

示例代码:

<script>
    $.ajax({
    // 1.url 请求地址
    url:'http://t.weather.sojson.com/api/weather/city/101010100',
    // 2.type 请求方式,默认是'GET',常用的还有'POST'
    type:'GET',
    // 3.dataType 设置返回的数据格式,常用的是'json'格式
    dataType:'JSON',
    // 4.data 设置发送给服务器的数据, 没有参数不需要设置

    // 5.success 设置请求成功后的回调函数
    success:function (response) {
        console.log(response);    
    },
    // 6.error 设置请求失败后的回调函数
    error:function () {
        alert("请求失败,请稍后再试!");
    },
    // 7.async 设置是否异步,默认值是'true',表示异步,一般不用写
    async:true
});
</script>

ajax方法的参数说明:

  1. url 请求地址
  2. type 请求方式,默认是'GET',常用的还有'POST'
  3. dataType 设置返回的数据格式,常用的是'json'格式
  4. data 设置发送给服务器的数据,没有参数不需要设置
  5. success 设置请求成功后的回调函数
  6. error 设置请求失败后的回调函数
  7. async 设置是否异步,默认值是'true',表示异步,一般不用写
  8. 同步和异步说明
  • 同步是一个ajax请求完成另外一个才可以请求,需要等待上一个ajax请求完成,好比线程同步。
  • 异步是多个ajax同时请求,不需要等待其它ajax请求完成, 好比线程异步。

ajax的简写方式:

$.ajax按照请求方式可以简写成$.get或者$.post方式

ajax简写方式的示例代码:

 <script>
    $(function(){
        /*
         1. url 请求地址
         2. data 设置发送给服务器的数据, 没有参数不需要设置
         3. success 设置请求成功后的回调函数
         4. dataType 设置返回的数据格式,常用的是'json'格式, 默认智能判断数据格式
        */ 
        $.get("http://t.weather.sojson.com/api/weather/city/101010100", function(dat,status){
            console.log(dat);
            console.log(status);
            alert(dat);
        }).error(function(){
            alert("网络异常");
        });

        /*
         1. url 请求地址
         2. data 设置发送给服务器的数据, 没有参数不需要设置
         3. success 设置请求成功后的回调函数
         4. dataType 设置返回的数据格式,常用的是'json'格式, 默认智能判断数据格式
        */ 
        $.post("test.php", {"func": "getNameAndTime"}, function(data){
            alert(data.name);
            console.log(data.time);
        }, "json").error(function(){
            alert("网络异常");
        });
    });


</script>

$.get和$.post方法的参数说明:

$.get(url,data,success(data, status, xhr),dataType).error(func)$.post(url,data,success(data, status, xhr),dataType).error(func)

  1. url 请求地址
  2. data 设置发送给服务器的数据,没有参数不需要设置
  3. success 设置请求成功后的回调函数
  • data 请求的结果数据
  • status 请求的状态信息, 比如: "success"
  • xhr 底层发送http请求XMLHttpRequest对象
  • dataType 设置返回的数据格式
    • "xml"
    • "html"
    • "text"
    • "json"
  • error 表示错误异常处理
    • func 错误异常回调函数