chrome报错:POST http://localhost:8080/TCCZB_Server/wsd/wsdchangethreshold.do 415
我看了网上很多解答但都是添加contentType: "application/json;charset=UTF-8"或者是json序列化,但我添加后依旧报错415
jsp:
<input type="text" class="form-control user-input" name="text" id="temperature"
placeholder="温度" data-pure-clear-button value="" autocomplete="off">
<input type="text" class="form-control user-input" name="text" id="humidity"
placeholder="温度" data-pure-clear-button value="" autocomplete="off">
<button type="button" class="btn btn-primary" id="update_btn">修改</button>
js:
$(function () {
console.log(appName);
var func = {
changethreshold: function () {
var a = $("#temperature").val(), b = $("#humidity").val();
var dataRow = {
temperature: a,
humidity: b
};
$.ajax({
url: appName + "/wsd/wsdchangethreshold.do",
type: "POST",
data: JSON.stringify(dataRow),
dataType: "json",
contentType: "application/json;charset=UTF-8",
success: function (result) {
$('#changethreshold').modal('hide');//隐藏模态框
if (result == "success") {
layer.msg("修改成功!", {icon: 1});
} else {
layer.msg("修改失败!", {icon: 5});
}
}
});
}
};
$("#update_btn").on('click', function () {
func.changethreshold();
});
});
controller:
@Controller
@RequestMapping("/wsd")
public class WSDController {
@Autowired
private WSDService wsdService;
@RequestMapping("/wsdchangethreshold.do")
@ResponseBody
public String changeThreshold(@RequestBody Threshold threshold) {
if (wsdService.changeThreshold(threshold.getTemperature(),threshold.getHumidity()) == true) {
return JSON.toJSONString("success");
}
return JSON.toJSONString("fail");
}
}
415 产生的根本原因是 ajax 提交数据时指定了 dataType: "json", 那么你的数据就不应该再用 JSON.stringify 了。调整操作:
data: dataRow,
dataType: "json",
其次,检查后台配置 SpringMVC 的配置类型要加上 json:
<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
<!-- 开启后缀匹配模式,.json请求会默认利用Jackson进行数据转换 -->
<property name="favorPathExtension" value="true" />
<property name="favorParameter" value="true" />
<property name="mediaTypes" >
<value>
json=application/json
xml=application/xml
</value>
</property>
</bean>
确认你传入的参数是否是JSON格式,返回参数可以不用JSON.toJSONString("success");你已经加了 @ResponseBody