先说$.post()它是JQ的 POST 请求功能,实例:
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>//jq在线地址
<script>
var id = '123';
var num = '1234';
$.post('test',{'id':id,"num":num},function (data) {
if(data.code == 0){
alert(data.msg);
}
});
// 'test'是方法名,就是要发送数据到的url.
// {"id":id,"num":num}这里面放要发送的数据.
// function(){} 这是请求成功后执行的回调函数.
</script>
$.ajax()写法实例:
var id = $('#user_id').val(); //获取id为user_id元素的值
var num = $('#number').val();
$.ajax({
url : "test/index", //test是控制器名,index是方法名
dataType: "json", //传输的数据格式为json
type: "post", //请求方式为post
contentType: "application/json; charset=utf-8", //编码方式
data:JSON.stringify({
//JSON.stringify()的作用是JavaScript值转换为 JSON 字符串
id : id,
number : num,
}),
success: function (data) {
//成功后执行的等价于 $.post 里的 function(){}
if(data.code == 0){
alert(data.msg);
}else{
alert(data.msg);
}
},
error: function () {
//失败后执行的函数
alert('请重试')
}
});
从实例上来看$.ajax 和 . p o s t 写 法 不 同 , .post 写法不同, .post写法不同,.post写法简洁一些,不过没有请求失败后执行的函数,大家按需求选取使用哪种。
和后台交互代码可看我的另一篇文章。
https://blog.csdn.net/weixin_42814467/article/details/104058709