前台jsp:
<script>
$(function() {
$("input.pvValue").keyup(function(){
var value = $(this).val();
var action = "admin_propertyValue_update.do";
var pvid = $(this).attr("pvid");
var json = {
"id": pvid,
"value": value
};
var jsonStr = JSON.stringify(json);
var parentSpan = $(this).parent("span");
parentSpan.css("border","1px solid yellow");
$.ajax({
type: "post",
url: action,
data: json,
/* data: jsonStr,
dataType:"json",
contentType : "application/json;charset=UTF-8", */
success:function(result){
if(result == "success")
parentSpan.css("border","1px solid green");
else
parentSpan.css("border","1px solid red");
}
});
});
});
</script>
ajax传值两种方式
- 方式一:前台传json对象时,不用加dataType和contentType。后台使用实体bean或者基本类型参数就可以接收,注意参数名称与json中的名字相同。不用在参数前加@RequestBody,若需要返回状态字符串需要在方法前加@ResponseBody,表示返回结果不会被解析为跳转路径,而是直接写入HTTP
响应正文中。
type: "post",
url: action,
data: json,
- 方式二:前台传json字符串时,需要加dataType和contentType。后台使用实体bean或者一个String类型参数可以接收,在参数前加@RequestBody,注意实体参数名称与json中的名字相同。不能使用相同参数名的其他基本类型接收。
type: "post",
url: action,
data: jsonStr,
dataType:"json",
contentType : "application/json;charset=UTF-8",
后台接收
- 若在后台使用String接收,需要使用JSON的jar包。
//把Json字符串转为JSON对象
JSONObject pvJSONObject = JSONObject.fromObject(value);
//把JSON对象转为实体对象
PropertyValue propertyValue = (PropertyValue)JSONObject.toBean(pvJSONObject, PropertyValue.class);
需要在maven中引入的jar包
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.1</version>
</dependency>