简体   繁体   English

如何使用ajax从java脚本中的servlet获取键值对?

[英]How to get key-value pairs from servlet in java script using ajax?

In my servlet I am creating a list key-value pairs with the help of a Map 在我的servlet中,我正在借助Map创建列表键值对

Map map=new HashMap();  
map.put("1", "john");  
map.put("2", "cris");  
map.put("3","patrik");  
JSONObject jsonMap=new JSONObject(map);  

out.print(jsonMap);  

I am calling the above servlet through ajax. 我正在通过ajax调用上述servlet。 I want to know how can I print all the key-value pairs in my javascript( with and without using jquery ) without knowing the key values? 我想知道如何在不知道键值的情况下( 不使用jquery )打印我的javascript中的所有键值对?

Any other idea how can I get both key-value pairs from servlet in javascript using ajax ? 任何其他想法如何使用ajax从javascript的servlet中获取两个键值对?

Thanks 谢谢

Though not safe, you can use eval to convert this response to a JSON object on the javascript side as follows: 虽然不安全,但您可以使用eval在JavaScript端将此响应转换为JSON对象,如下所示:

eval("var json = " + xmlHttpRequest.responseText);
for (var i in json) {
    // i and json[i] are the key and values respectively.
}

you can use the javascript arrays if you don't know the key. 如果您不知道密钥,则可以使用javascript数组。 ie

var resp = JSON.parse(responseText);
for(i=0; i<resp.length;i++){
    console.log(resp[i]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM