说明
jquery提交json格式数据,必须实现以下步骤:
- 必须post请求
- json数据要转成字符串
- 指定
contentType : "application/json"
前端代码
引入 jquery
<script src="js/jquery-1.11.0.js"></script>
关键代码
type:'post', // 必须是post请求
data: JSON.stringify({ //发给服务器端的数据,必须将json数据转成字符串
username:"admin",
password:"admin"
}),
contentType : "application/json", // 必须指定提交json格式数据
例子
function init(){
$.ajax({
url:'http://192.168.0.203:8082/login',
type:'post', // 必须是post请求
data: JSON.stringify({ //发给服务器端的数据,必须将json数据转成字符串
username:"admin",
password:"admin"
}),
contentType : "application/json", // 必须指定提交json格式数据
xhrFields: { // 带上cookie,不携带则删除
withCredentials: true
},
dataType:'json',//服务器端返回的数据格式是json
success:function(data){ //data:服务器端返回给浏览器端的数据
console.log(data);
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
// alert(textStatus);
// console.log(errorThrown);
}
});
}
init();//加载页面后直接调用init()函数
后端代码
springboot等框架可以通过注解处理,详见:
https://www.malaoshi.top/show_1EF5hAdgyMTy.html