Parse JSON response from Servlet - javascript

Ok, Ive got a Java Servlet returning some JSON (In Application/JSON format). To do this, im using the GSON libary.
The Servlets GET method takes one paramater, ID. The servlet seems to be working, For example,chrome shows my AJAX GET request returning the following when the [Booking]ID paramater sent is 1.
0: {WidgetID:46, BookingID:1, X:393, Y:50, Content:Test1}
1: {WidgetID:47, BookingID:1, X:337, Y:251, Content:Test2}
2: {WidgetID:48, BookingID:1, X:97, Y:198, Content:Test3}
The problem I have is with parsing this response. Here is my JS code:
loadPositions() {
var BookingID =
if (BookingID != null && BookingID != "null")
{
var data = {"id" : BookingID};
$.getJSON("Widget", data, function(data) {
// Successfully got all this bookings widgets as JSON, TODO: Parse this!
});
}
}
What should I put in the "TODO: Parse this!" section?
I want to foreach over all the elements, and grab their data. I really suck at this JQuery stuff.

In the todo section, you should do the following to loop through all the arrays:
$.each(data, function(index,value){
// here index=0 & value.WidgetID=46, value.BookingId = 1, use it as you would like to.
})

Have a look at jQuery .each()
http://api.jquery.com/jQuery.each/
and for a good example of what you want to do...
http://api.jquery.com/jQuery.getJSON/
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});

Take a look at
https://github.com/acobley/jBoggyAppy/blob/HectorV2-Cassandra-0.7.0/WebContent/Scripts/index.js
the ShowScrollingTags function.

Related

How to use jQuery forEach statement?

Note please. (I'm currently using the Spring Framework (MVC))
The value sent from Controller to ajax is ...
It looks like the picture above.
I am looping through the forEach statement for the values in that array, and I want to put the value into the tag.
So I wrote the code.
$(function()
{
$('#doctorSelect').change(function()
{
$('#selectGugan').show();
var doctor_idx = $(this).val();
$.ajax
({
type: 'POST',
url: 'selectDoctor.do',
data: {"d_idx":doctor_idx},
dataType: 'JSON',
success: function(sectionDate)
{
console.log(sectionDate);
var html = "<option value=''>Choice Doctor</option>";
var responseData = [];
responseData.push(sectionDate);
console.log(responseData);
$.each(responseData, function(key, value)
{
console.log("forEach statement in responseData :" + responseData);
//html+="<option value="+new_date+">"+new_date+"</option>";
});
$('#doctorSelect_2').html(html);
},
error: function(sectionDate)
{
console.log("data : " + sectionDate);
}
});
});
});
But unexpectedly, I do not get the key, value.
In fact, I don t know about the jquery forEach statement.
How do I set key, value?
I just want to bring those values and express it like this.
<option value="ri_idx">ri_startDate ~ ri_endDate</option>
How to set key, value or How to use jquery forEach statement ?
I am a beginner. I would appreciate it if you could give me an example.
In your case I am not sure why would you be doing this:
responseData.push(sectionData);
because this way you dont get an array of objects as I believe you thought you would, you simply will get an array with 1 element in it, which is many objects, so doing a forEach on that array will not help, because the value will be the multiobject element (not a single object that you could access properties).
What you want to do is iterate over your original objects, so your code should be something like this:
$.each(sectionDate, function(key, value){
// here you can access all the properties just by typing either value.propertyName or value["propertyName"]
// example: value.ri_idx; value.ri_startDate; value.ri_endDate;
});
Hope this helps!
In jQuery forEach working like this
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
If you are using Array for loop than key is array index and value values and if you are using javascript object then object key is key and value is object value for the particular key.
You can read more at jQuery documentation.
Just use property names in object. Check if this helps
$(document).ready(function() {
var responseData = [
{startdate: '2017-12-21', enddate: '2017-12-22', idx: '1'},
{startdate: '2017-11-21', enddate: '2017-11-22', idx: '1'},
{startdate: '2017-10-21', enddate: '2017-10-22', idx: '1'}
];
var html = '';
$.each(responseData, function(key, value) {
html += "<option value=" + value.startdate + ">" + value.startdate + "</option>";
});
$('#doctorSelect').html(html);
});

Accessing a value in JSON

I am trying to access the country names from this json -
https://restcountries.eu/rest/v1/all
This is my code for loading that json -
<script>
(function() {
var country = "https://restcountries.eu/rest/v1/all";
$.getJSON( country)
.done(function( data ) {
$.each(data, function(key, value) {
$('#mySelect').empty();
$('#myselect').append('<option>' + data.name + '</option>');
});
});
})();
</script>
The problem may be in data.name statement. I couldn't find any solution on my own. Plus, i am new to JSON. Any help or at least any comment to point my faults will be appreciated.
it should be value.name, data is the array you get from the api, value is each item in the array. also, remove empty as it's remove everything in each loop cyle...
see working code here

How to iterate objects in json whit jQuery

I am returning one JSON response from the server:
{'error':'true',fields:[[{'pk':2,'title':'test'}],{'votes':20,'cant':{1:0,2:3}}]}
Console Dev return
Object { error="true", fields=[2]}
I'm trying to get all the data fields[2], but not work, I'm doing something:
$.each(data.fields, function(i,item){
console.log(data.fields[i]);
})
Question: I know that I'm doing wrong, I want to access all the data in the order fields[2], pk and title.
Thanks.
You can fetch fields[2] using following:
$(data.fields).last()[0] // Give {votes: 20, cant: Object}
which you can use to iterate and get all data as:
var other_data = $(data.fields).last()[0]
$.each(other_data, function(key, value){
console.log('key : ' + key + ' value: ' + value);
});
Your code is need some corrections try this,
Demo
$.each(data.fields[1], function(i,item){
console.log(item);
})

Parsing json using jquery undefined

Hi I am new to json/jquery. Please help.
I have a database with list of cities/states. I get it and in the html document and use json_encode to get the json in a javascript object.
var json_obj = jQuery.parseJSON('<?php echo json_encode($query); ?>');
It looks like:
"[
{"city":"Aaronsburg","state_code":"PA"},
...
{"city":"Abbeville","state_code":"AL"}
]"
I am trying to use the following to access each city/state:
$.each(json_obj, function() {
$("<div>" + json_obj['state_code']+"/div>").appendTo('#test'); // I also tried json_obj.state_code
});
What I get in the output is:
undefined
...
undefined
What i need to do is actually print the city/state
Any help will be appreciated.
Thank you
The curreent value is passed by jQuery as:
$.each(json_obj, function(index, value) {
$("<div>" + value.state_code + "/div>").appendTo('#test');
});
Take a look at the specs.

How to pass an array of arrays into a function at JavaScript?

How can I define an array of arrays and pass that variable into a function so I can manipulate it at JavaScript?
As like:
JSP side:
object.method({ {"#id1",2}, {"#id2",3}...});
...
JS side:
var object= {
defaults: {
idSelector: "#id1"
},
method: function(options) {
if (options && !jQuery.isEmptyObject(options))
$.extend(this.defaults, options);
var that = this;
var opts = that.defaults;
//Try to reach every array step by step?
});
}
}
use json data format .
Convert your object into json string in your JSP page.
Parse that JSON string in your javascript.
Here's one of the ways to do that:
Your servlet can return a text, representing a json dictionary. Here's the documentation of a JSON API http://www.json.org/java/
Your javascript client code can fetch this json dictionary, something like:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
});
now items points to a bunch of <li> with your results
The functions' variable that will get the values should be like that(JSON format will be used):
defaults: [{
idSelector: '',
faqId: ''
}]

Categories

Resources