json回调函数没有效果,加各种alert()都不管用
原因是:
之前我只返回了一个字符串,并没有用json格式
后台必须传回json格式的字符串,才能回调,而且key值必须用双引号括起来
一定要注意json的格式不能错误
前台jsp:
$.post("goods/addGoods.do",
{
name:g_name,
code:g_code,
price:g_price,
stock:g_stock
},
function(data){//回调函数
$.each(data,function(i,n){
if(n.success == 1){
window.location.href="goods/list.do";
}else{
alert(n.error);
}
})
},
"json")//返回的数据必须也是json格式
后台:
// 商品编号是否存在
CheckIdDao check = new CheckIdDao();
if (check.checkId(code) == 1) {
json.append("[{\"error\":\"商品库存编号重复\"}]");
request.setAttribute("data", json.toString());
request.getRequestDispatcher("/data.jsp").forward(request, response);
return;
}
service = new AddGoodsService();
Integer i = service.addGoods(name, code, price, stock);
// 商品添加成功后转向到显示所有商品信息列表
if (i == 0) {
json.append("[{\"success\":\"1\"}]");
request.setAttribute("data", json.toString());
request.getRequestDispatcher("/data.jsp").forward(request, response);
}
//添加商品时使用失去焦点验证商品编号的在数据库中是否存在并给予友好提示
$("#goodsCode").bind("blur",function(){
var g_id = $("#goodsCode").val();
$.post("goods/checkId.do",//url
{id:g_id},//传递参数
function(data){//回调函数
//后台返回参数,如果是一个字符串默认带一行空白行,可以替换掉空白行
//也可以返回一个数字,直接处理
if(data == 1){
$("#message").html('<font color="red">商品编号已经存在</font>');
flag = false;
}else{
$("#message").html('<font color="blue">商品编号可以使用</font>');
flag = true;
}
},
//改成text,直接返回文本
"text")
});
两种常用的ajax请求
$.post()
$.ajax()