javascript 如何在java脚本方法中访问HashMap值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10327355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access HashMap values in java script method?
提问by Vicky
Here is my java code
这是我的java代码
public HashMap<Integer, Integer> getNoOfWidgetsFromUsername(final String username) //vikas- method to get pid from db.
{
HashMap<Integer, Integer> obMap = new HashMap<Integer, Integer>();
int numwidgets=getTotalWidgetsOfUser(PartnerID);
obMap.put(new Integer(1),PartnerID);
obMap.put(new Integer(2),numwidgets);
return obMap;
}
I put the above code in a function. I am calling that function from Javascript and returning values to Javascript.
我把上面的代码放在一个函数中。我正在从 Javascript 调用该函数并将值返回给 Javascript。
Here is my Javascript code.
这是我的 Javascript 代码。
JSClientService.getNoOfWidgetsFromUsername(username, {
callback : function(data) {
//here i want to print hashmap values.
}
});
How can I access the data on the Javascript side?
如何访问 Javascript 端的数据?
回答by Srikanth Kshatriy
It is a Java object, so you can not access it in javascript (i guess datawill be undefined in your case).
它是一个 Java 对象,因此您无法在 javascript 中访问它(我猜在您的情况下数据将是未定义的)。
Convert your java object to JSON object (something like this)
将您的 java 对象转换为 JSON 对象(类似这样)
JSONObject json = new JSONObject();
json.put("res",obmap);
then in your js callback function ()
然后在你的js回调函数()
callback : function(data) {
data = JSON.parse(data);
for(var i in data.res){
console.log(i); //key
console.log(data.res[i]); //value
}
}
code not tested
代码未测试