jquery ajax请求使用方法(jquery中的ajax封装方法详解)

jQuery库中支持AJAX的操作,功能十分完善详细请参考官方文档:https://www.jquery123.com/category/ajax/首先需要引入jquery文件!$.ajax({u

jQuery库中支持AJAX的操作,功能十分完善

详细请参考官方文档:

https://www.jquery123.com/category/ajax/

首先需要引入jquery文件!

$.ajax({  url: 'json.php',//设置请求地址 type: 'get',// 设置请求方式(不设置时默认为get)  // 设置的是请求参数  data: {id: 1, name: '张三'},  // 用于设置响应体的类型 注意跟data 参数没关系    dataType: 'json', success: function (res) {    // res 会自动根据服务端相应的    Content-Type 自动转换为对象     // 这是 jquery 内部实现的     console.log(res);   }});

json.php

<?php$xiaofang = array('name' => '小方', 'age' => 18);echo json_encode($xiaofang);

控制台显示:

jquery ajax请求使用方法(jquery中的ajax封装方法详解)

注意:设置了 dataType 之后,同时在服务端设置了 Content-Type之后,则不会管服务端设置了哪种文档类型!!!

现在,我们在 json.php 中设置 applicatioin/xml

<?php$xiaofang = array('name' => '小方', 'age' => 18);header('Content-Type: application/xml');echo json_encode($xiaofang);

控制台还是显示

jquery ajax请求使用方法(jquery中的ajax封装方法详解)

$.ajax({  url: 'time.php',   type: 'get',   beforeSend: function (xhr) {     // 在所有(open,send)之前执行     console.log('beforeSend', xhr); },    // 只有请求成功(状态码为200)才会执行这个函数    success: function (res) {       console.log('success', res);   },    error: function (xhr) {    // 只有请求不正常(状态码不为200)才会执行    console.log('error', xhr);    },    complete: function (xhr) {    // 请求完成:不管是成功还是失败都会触发    console.log('complete', xhr);   }});

运行结果:(这算是请求成功了)

jquery ajax请求使用方法(jquery中的ajax封装方法详解)

现在我们将存在的地址改变为一个不存在的地址再次请求

运行结果则会是

jquery ajax请求使用方法(jquery中的ajax封装方法详解)

正如方法名一样,$.get 就是使用 get 的请求方式对服务端进行请求

$.post 就是使用 post 的请求方式对服务端进行请求

两个方法的参数为:

第一个参数:请求地址

第二个参数:传递到服务端的参数(使用对象方式即可,也可使用 urlencoded 形式)

第三个参数:回调函数(接收响应体)

$.get('time.php', {id: 1}, function (res) {  console.log(res);}); $.post('time.php', {id: 1}, function (res) { console.log(res);});
$.get('time.php', 'id=1', function (res) { console.log(res);}); $.post('time.php', 'id=1', function (res) { console.log(res); });

如果我们必须要从服务端接收 JSON 格式的数据的话,那么就要使用 $.getJSON()了,并且一定要在服务端设置 'Content-Type: application/json'。不然拿到的数据是字符串类型的

例如:

json.php

$xiaofang = array('name' => '小方', 'age' => 18);echo json_encode($xiaofang);ajax$.getJSON('json.php', {id: 1}, function (res) { console.log(res); });

运行结果

jquery ajax请求使用方法(jquery中的ajax封装方法详解)

现在我们在服务端设置 'Content-Type: application/json'

<?php$xiaofang = array('name' => '小方', 'age' => 18);header('Content-Type: application/json');echo json_encode($xiaofang);

那么,运行结果为:

jquery ajax请求使用方法(jquery中的ajax封装方法详解)

本站部分文章来自网络或用户投稿,如无特殊说明或标注,均为本站原创发布。涉及资源下载的,本站旨在共享仅供大家学习与参考,如您想商用请获取官网版权,如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。
前端

js保留小数点后两位四舍五入(前端四舍五入保留两位小数实现方法)

2022-11-25 19:46:40

前端

html a标签怎么去掉自带蓝色(前端a标签属性的使用详解)

2022-11-25 19:46:48

搜索