如何在ajax中获取json值

时间:2015-03-25 07:00:07

标签: jquery ajax servlets

我有一个servlet,我在其中获取属性文件的值并将该值放在HashMap中。如何在ajax jquery中获取所有这些地图值并将每个地图值设置为每个文本框。我想在ajax中获取链接,appdb和appws并将其设置为文本框 - #links,#appsb,#appws。

SERVLET

               JSONObject json=new JSONObject();
              Map<String,String> obj = new HashMap<String,String>();
                if (lookfor != null) {
                    for (String look : lookfor) {
                        //System.out.println("looking for :"+look);
                        String value =  prop.getProperty(app+"_"+look);
                        if(app.equalsIgnoreCase(name)){
                        if(look.equalsIgnoreCase("Links")){
                            String links=(String) prop.getProperty(app+"_"+look,"Links");
                            //System.out.println("Links of"+" "+name + "is"+" " +links);
                            json.put("appLink", links);
                        }
                        if(look.equalsIgnoreCase("DataBase")){
                            String appdb=(String) prop.getProperty(app+"_"+look,"DataBase");
                            //System.out.println("DB of"+" "+name+"is"+" "+appdb);
                            json.put("appDB", appdb);
                        }
                        if(look.equalsIgnoreCase("WebServices")){
                            String appws=(String) prop.getProperty(app+"_"+look,"WebServices");
                            //System.out.println("WebService of"+" "+name+ "is"+" " +appws);
                            json.put("appWebService", appws);
                        }

1 个答案:

答案 0 :(得分:0)

以下是从Java Servlet返回JSON对象的方法:

response.setContentType("application/json");
// Get the printwriter object from response
// to write the required json object to the output stream      
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, 
// perform the following, it will return your json object  
out.print(jsonObject);
out.flush();

以下是使用AJAX获取JSON对象的方法:

$.getJSON('PropertyValueGetter?lookfor=Links', null,
        function(data){
            $("#links").val(data.appLink);
}); 

$.getJSON('PropertyValueGetter?lookfor=Database', null,
        function(data){
            $("#appdb").val(data.appDB);
}); 

$.getJSON('PropertyValueGetter?lookfor=WebServices', null,
        function(data){
            $("#appws").val(data.appWebService);
});