javascript 如何从 servlet 获取 JSON 对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6149811/
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 get JSON objects from servlet?
提问by AabinGunz
I am making a simple html servlet program where I need get JSON object from the servlet, and in html I am able to get the data, but how can i refer to each attribute?
我正在制作一个简单的 html servlet 程序,我需要从 servlet 获取 JSON 对象,并且在 html 中我能够获取数据,但是我如何引用每个属性?
Here is the servlet get
method
这是servletget
方法
PrintWriter out=response.getWriter();
StringBuffer emps = new StringBuffer("{employees:[");
emps.append("{fullname:\"Abhishek Raj Simon\"},{email:\"[email protected]\"}]");
emps.append("}");
out.println(emps);
JS to send
JS发送
function getJson()
{
var url_action="/temp/jsontest";
var form=document.forms["mainForm"];
var splitOutput;
var client;
var dataString;
if (window.XMLHttpRequest){
client=new XMLHttpRequest();
} else {
client=new ActiveXObject("Microsoft.XMLHTTP");
}
client.onreadystatechange=function(){
if(client.readyState==4&&client.status==200)
{
var res=client.responseText;
alert(res);
alert(client.responseText.employees.fullname); //DOES NOT WORK
alert(client.responseText.employees.email); //DOES NOT WORK
}
};
client.open("GET",url_action,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send();
and a simple form
和一个简单的形式
<form>
<input type="button" value="get me some json" onclick="getJson();">
</form>
When i click on the button, i get only 1 alert displaying {employees:[{fullname:"Abhishek Raj Simon"},{email:"[email protected]"}]}
How can i fetch Abhishek Raj Simon
and [email protected]
using fullname and email respectively?
当我单击按钮时,我只收到 1 个警报,显示{employees:[{fullname:"Abhishek Raj Simon"},{email:"[email protected]"}]}
如何分别获取Abhishek Raj Simon
和[email protected]
使用全名和电子邮件?
Edited after reading post from Artem
阅读Artem的帖子后编辑
my servlet
我的小服务程序
Gson gson = new Gson( );
List<Employee> employees = new ArrayList<Employee>();
Employee emp=new Employee();
emp.setFullname("Abhishek Raj Simon");
emp.setEmail("[email protected]");
employees.add(emp);
response.setContentType( "application/json");
out.println( gson.toJson( employees));
js part
js部分
var res=eval('(' + client.responseText + ')');
alert(res);
alert(res.employees.fullname);
alert(res.employees.email);
回答by Tomasz B?achowicz
I think you should slightly change the JSON that you send form the servlet: {employees:[{fullname:"Abhishek Raj Simon", email:"[email protected]"}]}
would work a bit better in that context.
我认为您应该稍微更改您从 servlet 发送的 JSON:{employees:[{fullname:"Abhishek Raj Simon", email:"[email protected]"}]}
在这种情况下会更好地工作。
I'd recommend jQuery as pap has also advised. The code would be:
我推荐 jQuery,因为 pap 也建议。代码将是:
$.getJSON('/temp/jsontest', function(data) {
var items = [];
for (employee in data.employees) {
items.push(employee.fullname + '<' + employee.email + '>');
}
alert('Employees: ' + items.join(', '));
});
In my opinion it is lot simpler and easier to understand than dealing with raw XHR. The jQuery $.getJSON
will do GET
for you, and then evaluate the JSON response so the function is presented with nice JSON representation of your data that is easy to manipulate.
在我看来,它比处理原始 XHR 更简单、更容易理解。jQuery$.getJSON
将为GET
您完成,然后评估 JSON 响应,以便函数以易于操作的数据的 JSON 表示形式呈现。
EDIT:
编辑:
After interesting discussion here is some more improvement you could introduce in order to replace the low-level code with proper JQuery-based implementation.
经过这里有趣的讨论,您可以引入更多改进,以便用适当的基于 JQuery 的实现替换低级代码。
<script>
$(document).ready(function() {
$("#json-button").click(function() {
$.getJSON('/temp/jsontest', function(data) {
var items = [];
for (employee in data.employees) {
items.push(employee.fullname + '<' + employee.email + '>');
}
alert('Employees: ' + items.join(', '));
});
});
});
</script>
<form>
<input id="json-button" type="button" value="get me some json">
</form>
回答by Artem Barger
I would suggest you to use GSONlibrary, which enables you to serialize Java object to json, to avoid writing it by yourself. If you do not want to use GSON, there are plenty of others libraries which uses same capabilities.
我建议您使用GSON库,它使您能够将 Java 对象序列化为 json,以避免自己编写它。如果您不想使用 GSON,还有很多其他库使用相同的功能。
//inside your get method
Gson gson = new Gson( );
List<Employe> employees = new ArrayList<Employe>( );
// populate your list here
response.setContentType( "application/json");
response.getWriter( ).println( gson.toJson( employees));
//end
then in javascript you can do as it's already suggested in other answers here. And do pay attention to update response content type.
然后在 javascript 中,您可以按照此处其他答案中已经建议的方式进行操作。并注意更新响应内容类型。
回答by Buhake Sindi
It's because you are receiving the JSON String but you're not converting it into a JSON Object. There's a eval()
function that evaluates your JSON String and returns a JSON Object.
这是因为您正在接收 JSON 字符串,但没有将其转换为 JSON 对象。有一个eval()
函数可以评估您的 JSON 字符串并返回一个 JSON 对象。
The following example should work (though untested).
以下示例应该可以工作(尽管未经测试)。
if(client.readyState==4&&client.status==200)
{
var res=eval('(' + client.responseText; + ')');
alert(res);
alert(res.employees[0].fullname);
alert(res.employees[0].email);
}
WARNING: I suggest reading the security concerns when using eval()
. Alternatively, go to JSON.organd download a Javascript JSON parser or use JQueryinstead.
警告:我建议在使用eval()
. 或者,转到JSON.org并下载 Javascript JSON 解析器或改用JQuery。
回答by pap
var res=client.responseText;
var temp = 'resObj=' + res;
eval(temp);
alert(resObj.employees.fullname);
JSON is just text, but in javascript syntax. You need to pass it through the "eval" method that will evaluate and execute the text as javascript.
JSON 只是文本,但采用 javascript 语法。您需要通过“eval”方法传递它,该方法将作为 javascript 评估和执行文本。
My advice, though, is to use jQuery or some other javascript framework to avoid having to mess with all that boiler-plate javascript.
不过,我的建议是使用 jQuery 或其他一些 javascript 框架,以避免与所有样板 javascript 混淆。