Different examples of ajax versus post handling json in jQuery

  • 2020-03-30 04:15:24
  • OfStack

Recently, when I was making user comments on the portal, I didn't use jquery for a long time. However, I didn't think that the post method was used to handle the json data of ajax callback. Unexpectedly, such a small problem hung for me for several hours, and then I was able to handle it with the ajax method, and I found that the original post method callback json must be eval, and the ajax method did the default processing. Please be careful.


function haha() {
jQuery.post("addComment!comment.action",
function aa(data) {
data = eval(data);//POST method must be added, the ajax method handles it automatically
alert(data[0].userId);
alert(data[0].userName);
},
"json"
);

jQuery.ajax({
type:"post",
url:"addComment!comment.action",
dataType:"json",
success: function aa(data) {
alert(data[0].userId);
alert(data[0].userName);
}
});
}

Background:


public String comment() {
try{
User u = new User("user", "koko");
list = new ArrayList<User>();
list.add(u);
//map.put("id", userId);
// JSONObject jb = JSONObject.fromObject(list); // name:"+userName +",
// info = jb.toString();
System.out.println(list);
}
catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
}

Configuration:


<package name="ajax" extends="json-default">
<action name="addComment" class="org.test.action.CommentAction">
<result type="json">
<param name="root">list</param>
</result>
</action>


Related articles: