web项目前端读取json数据不正常 ?

图片说明后台代码

@Override
    public String execute() throws Exception {
        Object obj=this.session.get(StaticString.ADMIN_INFO);
        Map<String, Object> map=new HashMap<String, Object>();
        if(obj!=null){
            AdminBean newAdmin =new AdminBean(this.name, this.password);
            ManageDao dao=AppDaoFactory.getInstance().getManageDao("manageDao");
            try{
                dao.updateAdmin(newAdmin);
                this.session.clear();
                map.put("message", "修改成功");
                map.put("success", true);
            }catch(AppException e){
                map.put("success", false);
                map.put("message", e.getMessage());
            }
            JSONObject json=JSONObject.fromObject(map);
            this.data=json.toString();
            return SUCCESS;
        }
        return "login";
    }

struts2
配置代码

 <action name="updateAdmin" class="com.iwm2.admin.actions.UpdateAdminAction">
            <result name="success" type="json">
                <param name="root">data</param>
            </result>
            <result name="login" type="redirectAction">login</result>
        </action

前端js代码

 $("#cpwa").click(function(){
        $("#ff").form('submit',{
            url:"updateAdmin",
            onSubmit:function(){
                return $(this).form('validate');
            },
            success:function(data){
                data=eval("(" + data + ")");
                if(data.success){
                    console.log(data);
                    console.log(data.success);
                    //alert(data.message);
                    location.href="login";
                }else{
                    console.log(data);
                    console.log(data.success);
                    alert(data.message);
                }
            }
        });
    });

结果却是无法读取json数据咋回事
console.log(data);能够打印出{"message":"修改成功","success":true}
console.log(data.message)却是undefined

没有设置一下返回数据类型吧,dataType: "json",

你的data是json啊,所以你把json转成js的object 然后再取值就ok了

eval转过data应该是json对象,你是执行到else语句打印出来的?

设置ajax返回数据类型属性 dataType: "json",就可以了

如果你将返回类型设置为,在action中不需要使用JSONObject.fromObject方法,直接返回MAP对象即可,struts2会自动将对象转化为json字符串。

var json = JSON.parse(string) ;//讲一个字符串转化为json对象。
var jsonString = JSON.stringify(json)//讲一个js对象转化为json字符串。