问题描述
- 利用ajax获得后台传过来的json,前端无法解析,对前端不是很深入,求指导
- 这是servlet:
package com.kj.servlet;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import net.sf.json.JSONArray;
import com.kj.entity.User;
import com.kj.service.IUserService;
import com.kj.service.impl.UserServiceImpl;public class MainPageServlet extends HttpServlet{
private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req HttpServletResponse resp) throws ServletException IOException { HttpSession session = req.getSession(); IUserService service = new UserServiceImpl(); String user_id = req.getParameter(""user""); //可通过传参实现当前页面第一层节点的转换 if(user_id == null){ //若无参数,使用当前登陆用户 user_id = session.getAttribute(""user"").toString(); } //当前主页第一节点的user User current_user = service.getUserMessageByid(user_id); List<User> sonUsers = service.getSonUser(current_user.getLeft_num() current_user.getRight_num() current_user.getUser_level()); List<User> thrid_user =new ArrayList<User>();; int i = 0; for(User user:sonUsers){ if(user.getUser_level() == current_user.getUser_level()+1){ //展示第二层级 switch(i){ case 0 : req.setAttribute(""user_1"" user); break; case 1 : req.setAttribute(""user_2"" user); break; default : req.setAttribute(""user_3"" user); break; } i++; }else{ thrid_user.add(user); } } //想将下面的array到前端,list转换为json没问题 JSONArray array = JSONArray.fromObject(thrid_user); resp.getWriter().write(array.toString()); req.setAttribute(""current_user"" current_user); req.getRequestDispatcher(""main.jsp"").forward(req resp);}@Overrideprotected void doPost(HttpServletRequest req HttpServletResponse resp) throws ServletException IOException { doGet(req resp);}
}
这是js:
$(function(){$.ajax({ url:""main.do"" type:""GET"" success:function(msg){ var user = eval(""(""+msg+"")""); alert(user.toString()); } error:function(er){ console.log(er); }});
})
这样写页面报错:Uncaught SyntaxError: Unexpected token < 。。。
解决方案
你用ajax异步请求,响应的时候却是跳转页面!不需要跳转页面!
解决方案二:
你先alert(msg),,弹出来看下是什么格式的数据
解决方案三:
ajax 写到write就行,不要用request或者response跳转,前面$.ajax({dataType : 'json'})给添加这个数据类型,就会自动将你传过来的 json值解析成
json数据,然后你就可以msg.key遍历了,key是你在后台写的
时间: 2024-10-26 22:30:38