JQuery 中的ajax
$.ajax()方法概述
$.ajax({
type: 'get',
url: 'http://www.example.com';
data: {name: 'zhangsan', age:'20'},
contentType: 'application/x-www-form-urlencoded',
beforeSend: function() {
return false
},
success: function (response){},
error: function(xhr){}
});
如果要传入json数据对象,则需要声明json
{
data: 'name=zhangsan$age=20'
}
{
contentType: 'application/json'
}
JSON.stringify({name: 'zhangsan', age: '20'})
使用案例:
在没有指定参数格式的时候,有两种参数传递方式,
data: { key: ‘value’ ....
}
和 data: 'key=value&....',
这两种方式最终都会被浏览器解析成data: 'key=value&...' 这种字符串形式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>$.ajax方法基本使用</title>
</head>
<body>
<button id="btn">发送请求</button>
<script src="/js/query.min.js"></script>
<script>
$('#btn').on('click',function(){
$.ajax({
//请求凡是
type: 'post',
//请求地址
url: '/base',
//向服务器端发送的请求参数
// data: 'name=wangwu&age=200',
data: {
name: 'zhangsan',
age: 100
},
//数据对象会默认转换成 name=zhangsan&age=100
//请求成功以后函数被调用
success: function(response){
//response为服务器端返回的数据
//方法内部会自动将json字符串转换为json对象
console.log(response);
},
//请求失败以后函数被调用
error: function(xhr){
console.log(xhr)
}
})
});
</script>
</body>
</html>
如果指定了传递参数的类型,就必须使用指定格式的参数
假如指定:contentType: 'application/json',
外部传递一个params对象,在ajax内部需要使用JSON.stringify(params) 进行json解析。
var params = {name: 'wangwu', age: 300}
$('#btn').on('click', function() {
$.ajax({
//请求方式
type: 'post',
//请求地址
url: '/user',
data: JSON.stringify(params),
//指定参数的格式类型
contentType: 'application/json',
//请求成功以后函数被调用
success: function(response) {
//response为服务器端返回的数据
//方法内部会自动将json字符串转换为json对象
console.log(response);
}
});
}
如果想在请求之前发送,截断,使用如下方法:
var params = {name: 'wangwu', age: 300}
$('#btn').on('click', function() {
$.ajax({
//请求方式
type: 'post',
//请求地址
url: '/user',
data: JSON.stringify(params),
//指定参数的格式类型
contentType: 'application/json',
//在请求发送之前调用
beforeSend: function() {
alert('请求即将发送')
//false 代表请求不会被发送
return false
}
//请求成功以后函数被调用
success: function(response) {
//response为服务器端返回的数据
//方法内部会自动将json字符串转换为json对象
console.log(response);
}
});
}