jquery ajax请求使用方法(jquery中的ajax封装方法详解)
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);控制台显示:

注意:设置了 dataType 之后,同时在服务端设置了 Content-Type之后,则不会管服务端设置了哪种文档类型!!!
现在,我们在 json.php 中设置 applicatioin/xml
<?php
$xiaofang = array('name' => '小方', 'age' => 18);
header('Content-Type: application/xml');
echo json_encode($xiaofang);控制台还是显示

$.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);
}
});运行结果:(这算是请求成功了)

现在我们将存在的地址改变为一个不存在的地址再次请求
运行结果则会是

正如方法名一样,$.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); });运行结果

现在我们在服务端设置 'Content-Type: application/json'
<?php
$xiaofang = array('name' => '小方', 'age' => 18);
header('Content-Type: application/json');
echo json_encode($xiaofang);那么,运行结果为:

除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.cn/ajax/1101.html
原文地址:https://tangjiusheng.cn/ajax/1101.html
