parsererror ajax

前台按钮单击事件:
[code="java"]
$("#cmd_test").click(function (){
alert("cmd_test");

$.ajax({

url: "testActionJson.action",
dataType:"json",
type:"post",
data: {"id":1,"name":"john","age":30},
success: function(data){
alert(data);

},
error:function(request,msg,errObj){
alert(msg);
}

});

[/code]

[code="java"]
后台Action中的testActionJson方法:
public void testActionJson() {
ActionContext ac=ActionContext.getContext();
HttpServletRequest request=(HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST);
HttpServletResponse response=(HttpServletResponse) ac.get(ServletActionContext.HTTP_RESPONSE);
System.out.println("testActionJson");
String name=request.getParameter("name");
System.out.println(name);
try {
response.getWriter().print(name);

    } catch (Exception e) {
        System.out.println(" error:");
        e.printStackTrace();
    }

}

[/code]

奇怪的是在单击按钮提示parsererror错误,但跟踪发现是有从后台action中返回name变量值john到后前台的,在后台输出也是有值的,但为什么发生error呢。

6个回答

[code="javascript"]
$("#cmd_test").click(function (){

alert("cmd_test");

$.ajax({

url: "testActionJson.action",

dataType:"json",

type:"post",

data: {"id":1,"name":"john","age":30},

success: function(data){

alert(data.type);
alert(data.msg):
},

error:function(request,msg,errObj){

alert(msg);

}

});
[/code]

[code="java"]
//以下为封装json格式。懒的自己写了,从以前的项目中找了块。你可以自己改的。
Map map = new HashMap();
map.put("type", "auth_user");
map.put("msg", "您填入的用户证件号为已存");

StringBuilder sb = new StringBuilder();
sb.append("{");
Set keySet = map.keySet();
for (String key : keySet) {
sb.append("\"").append(key).append("\":\"").append(map.get(key))
.append("\"").append(",");
}
sb.deleteCharAt(sb.lastIndexOf(","));
sb.append("}");
response.setContentType("text/json;charset=GBK");
PrintWriter pw = response.getWriter();
pw.write(sb.toString());
pw.close();
[/code]

response.getWriter().print(string) print的东西好像要是json字符串吧,我估计是没把输出结果包装成json字符串导致前台解析出了异常

你用chorme等浏览器调试一下js,看看返回来的东西是什么,在哪一行抛出了parsererror?

[quote]$("#cmd_test").click(function (){

alert("cmd_test");

$.ajax({  

url: "testActionJson.action",

dataType:"json",

type:"post",

data: {"id":1,"name":"john","age":30},

success: function(data){

alert(data);

},

error:function(request,msg,errObj){

alert(msg);

}

}); [/quote]
你指定的返回类型为json,那么回调函数是按照json格式来解析的,但你的后台相应返回的不是json格式,所以解析错误。

要不该响应结果为json格式的{'k':'v','k1':'v1'}要不你就将dataType指定为‘html',因为jquery对于dataType的json格式有如下说明[quote]"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)[/quote]

{'state':'ok'}

那问题不再json字符串了,你调试一下客户端,看看有什么问题

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问