[英]Parsing a JSON object (list of object) through Javascript and loop in it?
Ok, I know there's something wrong but I can't understand what. 好吧,我知道有什么不对,但我无法理解。
I read an ArrayList of Service (in JSON mediatype) from a web service that I wrote. 我从我写的Web服务中读取了一个服务的ArrayList(JSON mediatype)。 Going to that address returns me the json string. 转到该地址会返回json字符串。
Now I'm trying to make a web page for showing that values and seeing the changes making to the page a request every 3 secs. 现在,我正在尝试制作一个网页,用于显示值,并每隔3秒查看对页面进行更改的请求。
How can I parse it, or use it? 我该如何解析或使用它? Read lot and more and I'm still to the start.. 阅读很多,我还在开始..
[Is not possible to pass this object to the JSP and parse, loop and everything with JSTL? [无法将此对象传递给JSP并使用JSTL解析,循环和所有内容? That would be awesome!] 那将是真棒!]
Here the js code: 这里是js代码:
<script type="text/javascript">
setInterval(function(){
$.ajax({ url: "/MyApp/rest/display", success: function(data){
var objs = $.parseJSON(data);
$.each(objs, function(i,service) {
$("#service").append('<p>'+service+'</p>');
});
}, dataType: "json"});
}, 3000);
</script>
I've a <div id="service">
我有一个<div id="service">
EDIT: Almost there! 编辑:差不多了!
Now I've this: 现在我这样:
<script type="text/javascript">
setInterval(function(){
$.ajax({ url: "/myApp/rest/display", success: function(data){
$.each(data, function(i,service) {
var cont = 1;
var newdiv = document.createElement('div');
newdiv.setAttribute('id', "service"+i);
$("#service"+i).html('<p>'+service.serviceId+" "+service.queue.lastNumber+'</p>');
document.getElementById("services").appendChild(newdiv);
cont++;
});
}, dataType: "json"});
}, 5000);
</script>
It gets the updates and all (nice!) but I've one problem: it keeps creating new divs inside the bigger one (empty divs). 它得到了更新和所有(很好!)但我有一个问题: 它不断在较大的div(空div)中创建新的div 。 How can I avoid this? 我怎么能避免这个?
EDIT2: EDIT2:
Nevermind, I've done! 没关系,我做完了! Just add this line before the appendChild: 只需在appendChild之前添加此行:
if(!$("#service"+i).length)
Works like a charm. 奇迹般有效。 Thanks! 谢谢!
With JQuery you do not need to parse the data
since it is already parsed as JSON when you set the dataType: "json"
. 使用JQuery,您不需要解析data
因为在设置dataType: "json"
时它已经被解析为JSON。
$.ajax({
url: "/MyApp/rest/display",
success: function(data) {
$.each(data, function(i,service) {
$("#service").append('<p>'+service+'</p>');
});},
dataType: "json" });
PS. PS。 If that doesn't work, please post the JSON that is being returned by your AJAX call. 如果这不起作用,请发布您的AJAX调用返回的JSON。
EDIT: Here is the JSTL way of doing things: Create a JSF or JSP that does NOT return a full HTML page but just what you want inside the #service
div. 编辑:这是JSTL的处理方式:创建一个JSF或JSP,它不返回完整的HTML页面,但只是你想要的#service
div。 Lets call the page doit.jsp
. 让我们调用doit.jsp
页面。 Now we can just use ajax to put that in the #service
div. 现在我们可以使用ajax将它放在#service
div中。
$.ajax({
url: "doit.jsp",
success: function(data) { $("#service").html(data); });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.