Y_Bei
2016-03-09 08:43
采纳率: 25%
浏览 3.3k
已采纳

利用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;

@Override
protected 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);
}

@Override
protected 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 < 。。。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

  • kiansoung 2016-03-09 09:15
    最佳回答

    你用ajax异步请求,响应的时候却是跳转页面!不需要跳转页面!

    评论
    解决 无用
    打赏 举报
查看更多回答(2条)