在js中请求ajax,把jsp中的一个Cno传到Servlet中
$.ajax({
type :"post",
url : "ShowDetail?Cno="+Cno,
async:false,
dataType : "json",
success : function(data) {
},
error : function() {
var student =eval("(" +result +")");
alert(student.Cth1);
}
});
在Servlet中获取后台值,并out.print JSON格式
out.print("[{'Cno':'"+Cno+"','Cth1':'"+cd.get(0).getCth1()+"']});
应该如何通过ajax获取这里面的值
我通过 var student =eval("(" +result +")"); 的方法,但是student.Cth1获取不了值
这里用Error是因为Success没有反应。
你的jquery版本>1.4,json格式不标准是不会执行回调的,因为jquery1.4+指定dataType为json,标准json格式字符串才会执行回调
out.print("[{\"Cno\":\""+Cno+"\",\"Cth1\":\""+cd.get(0).getCth1()+"\"]});
$.ajax({
type :"post",
url : "ShowDetail?Cno="+Cno,
async:false,
dataType : "json",
success : function(data) {
alert(data[0].Cth1);///你返回的是json数组数组,不是json对象
},
error : function() {
// var student =eval("(" +result +")");
// alert(student.Cth1);
}
});
student[0].Cth1
你这传过来的应该是个json数组,所以不应该直接用对象获取。应该写成result[0].Cth1.
如果再获取不到 你再尝试使用var student =eval("(" +result +")") student[0].Cth1.
你调试下,输出后台的json,然后修改ajax的success分支,这个分支的参数data就是你后台返回的JSON数据。
看看代码到底走到哪里错了:后台输出、success/error都添加调试信息。祝好!
$.ajax({
type :"post",
url : "ShowDetail?Cno="+Cno,
async:false,
dataType : "json",
success : function(data) {
alert("success.");
//后台返回的JSON数组访问
if(data!=null&&data.length>0){
var student = data[0];
console.log("student cno:"+student.cno);
console.log("student Cth1:"+student.Cth1);
}
},
error : function() {
alert("error .");
}
});
你断点测试,看后台的方法响应了吗