jquery - 将 json 对象传递给 restController 时出现 400(错误请求)
问题描述
我正在发送一段json object using ajax
时间RestController
,将其传递给控制器,发生以下错误:
vendor.js:8630 PUT http://localhost:8015/campasAdmin/master/updateState 400(错误请求)
这是我的ajax调用:
$(document).on("click","#stateSave",function(event){
var stateId=parseInt($("#stateId").val());
var countryId=parseInt($("#countryName").val());
alert(countryId);
var stateName=$("#stateName").val();
//parseInt($('#numberValue').val(), 10);
var JSONObject= {
"stateId":stateId,
"countryId":countryId,
"stateName":stateName
};
var myJSON = JSON.stringify(JSONObject);
//var jsonData = JSON.parse(JSONObject);
console.log(JSONObject);
var url = contextPath+"/master/updateState";
$.ajax({
url : url,
type:"put",
date:myJSON,
contentType:'application/json; charset=utf-8',
async: false,
success:function(response)
{
console.log(response.status);
if(response.status)
{
$(".editor").hide();
$("#countryTable tbody tr").remove();
$(".mainContainer").show();
stateList();
Alert.info(response.data);
}
else{
Alert.warn(response.errorMessage);
}
}
});
});
myJSON 对象如下所示:
{stateId: 1, countryId: 1, stateName: "up"}
countryId : 1
stateId : 1
stateName :"up"
这是我的控制器和放置方法:
@RestController
@RequestMapping(value="/master")
public class MasterController
{
@Autowired
private MasterServiceInter service;
private HttpHeaders headers = null;
Map<String, Object> message = new HashMap<String, Object>();
//update state
@PutMapping("/updateState")
public ResponseEntity<Map<String, Object>> updateState(@RequestBody State theState) {
ResponseEntity<Map<String, Object>> responseEntity=null;
try {
System.out.println(theState);
boolean res =service.updateState(theState) ;
if (res) {
headers.add("head", "State");
message.put("status", true);
message.put("data", "State has been updated successfully !");
responseEntity= new ResponseEntity<Map<String, Object>>(message, headers, HttpStatus.CREATED);
} else {
headers.add("head", "null");
message.put("status", false);
message.put("errorMessage", " State has not been updated successfully ! ");
responseEntity=new ResponseEntity<Map<String, Object>>(message, headers, HttpStatus.NOT_FOUND);
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return responseEntity;
}
}
我认为它解析JSON对象的问题,我无法追踪它,请帮助我。
解决方案
抱歉,每个人都在我的 ajax 代码中输入了雾
$.ajax({
url : url,
type:"put",
date:myJSON, // here is the mistake
contentType:'application/json; charset=utf-8',
async: false,
success:function(response)
{
}
});
它应该是
$.ajax({
url : url,
type:"put",
data:myJSON,
contentType:'application/json; charset=utf-8',
async: false,
success:function(response)
{
}});
谢谢大家,并堆积如山
推荐阅读
- css - 从 html 中的交互式表格更新绘图
- html - 在 Firefox 上隐藏消息“找不到支持格式和 MIME 类型的视频”
- c# - 如何在 C# 中反序列化奇怪的 JSON 格式
- macos - 无法在mac上复制和安装android studio
- scala - 在 Apache Spark 中使用 RESTful API 并转换为 Dataframe
- rxjs - 如何测试使用 rxjs 弹珠发出分组事件的可观察对象?
- c# - 以编程方式减少 TIME_WAIT 或 CLOSE_WAIT
- javascript - 如何排除 gulp src 中的路径?
- javascript - 访问未知的 Firebase 路径
- php - Silverstripe 4 - 未找到身份验证器类