weixin_42301016
weixin_42301016
2009-04-21 16:00

struts2中用上json后,页面取不到想要的值

  • struts

开发环境struts2+Hibernate+spring用了json,不知道我的action写的对不对,但是页面能取到json值,就是用上“.”后取不到值。该怎么来取值呢?
Action类:
public class GoodsAction extends ActionSupport{
private T01 goods;
private String bianhao;
private String jsonchar;
//省略getter/setter
@SuppressWarnings("unchecked")

public String queryGoodsInfo()

{
System.out.println("bianhao= "+bianhao);
goods=goodsService.queryGoodsInfo(bianhao);

    jsonchar="{\"mingcheng\":\""+goods.getT01d04()+"\",\"guige\":"+goods.getT01d08()+"}";       

     System.out.println(jsonchar);
    //[color=red]这个在后台可以打印出来{"mingcheng":"2","guige":null}[/color]
    return SUCCESS;

}

配置action的.xml文件是:



jsonchar




前端页面addplan.jsp:
function changes() {

    if(bXmlHttpSupport) {
        var bianhao = document.getElementById("t27d03").value;
        var sUrl = '../../goods/QueryGoodsInfo.action?bianhao='+bianhao;
        var oRequest = new XMLHttpRequest();
        oRequest.onreadystatechange = function() {
            if(oRequest.readyState == 4) {                    
                var oBook = eval('(' + oRequest.responseText + ')');

                var a={"name":"lw"};
                alert(a.name); 
                这句话可以弹出结果:lw

                alert("oBook="+oBook);
                这句话也可以弹出结果: {"mingcheng":"2","guige":null},

               但是这句话 alert("mingcheng= "+oBook.mingcheng)就弹出undifined,不知道为什么?请指点;
                //document.write(oBook.mingcheng);
                document.getElementById("t27d04").value =oBook.mingcheng;
            }
        };
        oRequest.open('POST', sUrl);
        oRequest.send(null);
    }
}

[b]问题补充:[/b]

先多谢两位,我还有不明白的地方;
1.Map map = new HashMap();map.put("uid", userinfo.getPassportId());map.put("nickName", userinfo.getNickName());[color=red]JSONObject json1 = JSONObject.fromObject(map);[/color]
huangnetian (高级程序员) 2009-04-21 采纳为答案

JSONObject是哪里来的?是不是用了什么类包?

2.我试了alert(typeof oBook);发现返回的是String,怎么才能返回对象呢?多谢;
[b]问题补充:[/b]
lovewhzlq (架构师) 2009-04-21 :

import org.stringtree.json.JSONWriter;

JSONWriter writer = new JSONWriter();
Map map = new HashMap();
map.put("mingcheng",goods.getT01d04());
map.put("guige",goods.getT01d08());
String jsonStr = writer.write(map);
这样前端页面获得的还是String[color=red],(var oBook = eval('(' + oRequest.responseText + ')');
)[/color],是不是不能这样获取啊?怎么才会是Object呢?还是不懂;

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

8条回答