关于ajax传值与后台如何接收的一些总结

 关于ajax传值与后台如何接收的一些总结
 
 对于传的参数比较少可以采用以下方法1
 前台:
 $.ajax({
url:'/college/delete',
type:'POST',
dataType:'json',
data:{"collegeId":collegeId},
success:function (data) {
    if(data.success){
        Modal.alert('删除成功!',function () {
            window.location.reload();//刷新

        })
    }

}

})
后台:
Long collegeId = HttpServletRequestUtil.getLong(request,“collegeId”);

对于需要传的参数比较多时采用以下方法2:
前台:
$(’#dosave’).click(function () {
var college = {};
college.collegeName = $(’#collegeName’).val();
college.code = $(’#code’).val();
$.ajax({
url:’/college/add’,
type:‘POST’,
data:JSON.stringify(college),
contentType:‘application/json’,
success:function (data) {
if(data.success){
$(’#myModal’).modal(‘hide’);
window.location.reload();//刷新
}else {
Modal.tipFailure(data.errMsg);
}
}
})
})
后台:
private Mapadd(@RequestBody College college, HttpServletRequest request) {
}

对于含有图片或者含有其他参数时可以采用formData()方法3:
前台:
$(’#submit’).click(function () {
var shop = {};
shop.shopName = $(’#shop-name’).val();
shop.shopAddr = $(’#shop-addr’).val();
shop.phone = $(’#shop-phone’).val();
shop.shopDesc = $(’#shop-desc’).val();
var verifyCodeActual = KaTeX parse error: Expected 'EOF', got '#' at position 3: ('#̲j_captcha').val…(’#shop-category’).find(‘option’).not(function () {
return !this.selected;
}).data(‘id’)
};
shop.area = {
areaId:$(’#area’).find(‘option’).not(function () {
return !this.selected;
}).data(‘id’)
};
var shopImg = $(’#shop-img’)[0].files[0];
var formData = new FormData();
formData.append(‘shopImg’,shopImg);
formData.append(‘shopStr’,JSON.stringify(shop));
formData.append(‘verifyCodeActual’,verifyCodeActual);
$.ajax({
url:(isEdit ? editShopUrl:registerShopUrl),
type:‘POST’,
data:formData,
contentType:false,
processData:false,
cache:false,
success:function (data) {
if(data.success){
$.toast(‘提交成功!’);
}else {
$.toast(‘提交失败!’+data.errMsg);
}
$(’#captcha_img’).click();
}
})
})
});
后台:
String verifyCodeActual = HttpServletRequestUtil.getString(request, “verifyCodeActual”);
String shopStr = HttpServletRequestUtil.getString(request,“shopStr”);
ObjectMapper mapper = new ObjectMapper();
Shop shop = null;
try{
shop = mapper.readValue(shopStr,Shop.class);
}catch (Exception e){
modelMap.put(“success”,false);
modelMap.put(“errMsg”,e.getMessage());
return modelMap;
}
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
if(commonsMultipartResolver.isMultipart(request)){
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
shopImg = (CommonsMultipartFile)multipartHttpServletRequest.getFile(“shopImg”);

如果中间有错误地方,还望大神指点!!

你可能感兴趣的:(java)