ajax—json返回undefined,大家帮忙看看,非常感谢了!!!!
js代码:
var url="${pageContext.request.contextPath}/updateHSwitch.action";
$.post(url,{isID:hsID,isSwitch:hsSwitch,dataType:"json",success:function(jsonres){
alert(jsonres); //s弹出undefined
var json = eval("(" + jsonres + ")");
alert(json); //s弹出undefined
}
});
action代码:
public String updateHSwitch() {
System.out.println(".............");
if(isID==100) return "ERROR";
dataList=hostSwitchBiz.getHostSwitch(isID); //根据ID获取信息
for (int i = 0; i < dataList.size(); i++) {
hostswitch=(SwHostswitch)dataList.get(i);
}
hostswitch.setIsSwitch(isSwitch); //替换开关状态数据
explanList=hostSwitchBiz.updateHSwitch(hostswitch); //更新整条数据
JSONArray jsonres=JSONArray.fromObject(explanList);
System.out.println(jsonres.toString());
//输出[{"isCommand":"#58008# ","isOpenExplain":"语音提示 ","isState":"内部空号音提示","isSwitch":"0","isShutExplain":"听空好音 ","isExplain":"内部空好音提示:1 语音提示,0 听空号音","isId":8}]
return "jsonres";
}
xml配置:
你这段代码,有几个地方需要调整一下。
$.post() 换成 $.ajax();
dataType:"json",这个属性我不清楚对$.post()也是起作用的。
第二个是action里面 按需(前端要什么就给什么)向前台返回数据比较合理
直接将jsonres.toString();通过Response对象返回到前台。
这个也就不需要了
return null;就行了。
type="json" 会对所有提供get方法的字段进行处理。如果变量比较多就不好玩了。
也不用非要用json这样的修饰,你就当是字符串,返回到前端像你用eval 也有json2.js这样的工具类,在处理一下就OK了。
explanList=hostSwitchBiz.updateHSwitch(hostswitch); //更新整条数据
问一下,你这个地方的explanList有getter方法吗???
return "jsonres";
你return一个jsonres字符串 那你前面处理的jsonres对象干什么用?
jsonres
而且也不用evel了吧
首先我确认下,你放到前台json显示的是explanList此变量吗?然后是你有用firebug看过后台的返回值吗?
另外我给个意见,你前台的success:function(jsonres){ } 这个jsonres应该形式是{"explanList":[{"isCommand":"#58008# ","isOpenExplain":"语音提示 ","isState":"内部空号音提示","isSwitch":"0","isShutExplain":"听空好音 ","isExplain":"内部空好音提示:1 语音提示,0 听空号音","isId":8}] },所以var json = eval("(" + jsonres + ")"); 这个地方的处理应该是var json = eval("(" + jsonres.explanList + ")"); 当然这是你结果有返回的后话了
用response.getWriter().print(str);
eval少用吧
既然用jquery了就$.parseJSON(str);
1.将JSONArray转化成字符串写入到响应中
response.getWriter().print(jsonres.toString());
2.Action当中只需要返回空即可。
return null;