I want to pass 3 JSON to front end. I can pass all 3 individually. I did this to check if its working.
I do it this way:
response.getWriter().write(json.toString());
I read on one of the post on here that you could put the create a json array and send the array to the Ajax call.
So I tried doing this:
String json = "["+ json1.toString() + "," + json2.toString() + "," + json3.toString() + "]";
response.getWriter().write(json.toString());
In the client side of the house:
$.ajax({
data: {param1: 'p1', param2: 'p2', param3: 'p3', param4: 'p'},
dataType: 'json',
url: './GetDataServlet',
type: 'POST',
success: function(data) {
var data1 = data[0];
var data2 = data[1];
var data3 = data[2];
$.each(data1 , function(i, val) {
$("#personal_data").append("<p> val.firstname </p>")
$("#personal_data").append("<p> val.lastname </p>")
)};
$.each(data2 , function(i, val) {
$("#department_data").append("<p> val.departmentid </p>")
$("#demartment_data").append("<p> val.departmentname </p>")
)};
//Not attaching the entire code, because it's quite long. :)
},
error: function() {
alert("An error occured while attempting fetch data.");
}
});
How can you pass multiple JSONs to the client side when you make an $.ajax call.
Thanks,
You could try sending a single array of the three objects. [Obj1 , Obj2 , Obj3]
If the three objects returned depend on the previous objects sent (say Obj2 depends on Obj1.X property is true or false you can have three separate calls
var firstResult = $.ajax({
url : firstUrl
... other details
});
var firstResult.done(function(Obj1){
if(Obj1.X){
$.ajax({
url : secondUrl
... other details
});
... other calls
});
In properly formed JSON and AJAX requests/responses, 1 call delivers 1 JSON string.
Of course, you can compose those JSON strings however you want within the allowable JSON structure. In your case, there is absolutely nothing wrong with composing three JSON objects within a JSON array wrapper.
I think perhaps your only issue is here:
String json = "["+ json1.toString() + "," + json2.toString() + "," + json3.toString() + "]";
response.getWriter().write(json.toString());
The String json that you build is already a string, so you don't need to call toString() on it again. Just do:
String json = "["+ json1.toString() + "," + json2.toString() + "," + json3.toString() + "]";
response.getWriter().write(json);
I was trying to do the same thing. I wanted to pass three json objects to my javascript. I tried making the three json objects into one json array and passing it,but it complicated the situation greatly.
I found that passing a string separated by a character I chose "%" is much easier.
String json1 = "....";
String json2 = "....";
String json3 = "...";
String toApp = json1 + "%" + json2 + "%" + json3;
Then in javascript you can split the text with
var split = line.split("%");
Finally a json object can be made from split[0], split[1] and split [2].
var c1= new Object();
c1.property1="test";
c1.property2="test";
var c2= new Object();
c2.property1="test";
c2.property2="test";
var data = { 'c1': c1, 'c2': c2 };
var parameters1 = JSON.stringify(data);
In ajax call pass parameters1 as data.
[WebMethod]
public static bool TestMethod(Object c1, Object c2)
{
}
Related
I have a JSON object of the type
[
{
at: "own",
op: "in_between",
va: ["str", "jan"]
},
{
a: 'alas',
op: 'cont',
va: [10, 20]
},
.
.
.
]
I want to pass this as a GET query parameter. Now I could just stringify it and pass it as something like this
?q={"0":{"at":"own","op":"in_between","va":["str","jan"]},"1":{"at":"alas","op":"cont","va":[10,20]}}
However I would prefer to serialize it in a different format. Something like
q[]=at:"own"|op:"in_between"|va:["str","jan"]&q[]=at:"alas"|op:"cont"|va:[10,20]
(I saw a this kind of format being used in Amazon's search filters. Any other format suggestions are welcome. My main goal is to shorten the URL)
So i was able to serialize it by just concatenating to a string
let q = "";
data.forEach(function(i) {
q = q.concat(`q[]=at:"${i.at}"|op:"${i.op}"|va:[${i.val}]&`);
});
return q.slice(0,-1);
Similarly I have an extractor
let qArray = q.split('&');
let qParse = [];
qArray.forEach(function(i) {
i = JSON.parse('{' + i.substring(4).split('|').join(',') + '}');
q.push(i);
});
However this only works well for q[1] where q[1]['va'] has an integer array. It needs to also work for q[0] with the string values
Also is there any better way of serializing and extracting it in these kinds of forms?
Thanks in advance!
As said previously in the comments, I was wondering if CSV wouldn't work for what you want. It's kind of easy to parse. Would this work (assuming filters is your array) ? :
let params = "?q=;at,op,va;";
filters.forEach(function(fil) {
params += fil.at + "," + fil.op + "," + JSON.stringify(fil.va) + ";";
})
If you want to store queries to make percentage, you'd just have to remove first three characters. I'm also supposing that all your dictionnaries follow the same structure. Hope this works for you
I received a response from MY ajax as follows
"{\"analgesicTax\":false,\"unitPriceRequired\":false,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\"}"
After calling JSON.parse(result), the result looks like
{"analgesicTax":false, "unitPriceRequired":false, "toConsumer":true, "toRetailer":true, "taxName":"1"}
Up until that point everything seems to be ok. However, when I tried to print my key/value pairs by using following code
var data = JSON.parse(result);
console.log(data);
console.log(data.analgesicTax);
for (var prop in data) {
console.log(prop+"is" + data[prop]);
I tried both using with and without JSON.parse() but the output is same as follows.
0is{
1is"
2isa
3isn
4isa
5isl
6isg
7ise
8iss
9isi
10isc
11isT
12isa
13isx
14is"
15is:
16isf
17isa
18isl
19iss
20ise
21is,
22is"
23isu
24isn
25isi
26ist
27isP
28isr
29isi
30isc
31ise
32isR
33ise
34isq
35isu
36isi
37isr
38ise
39isd
40is"
41is:
42isf
43isa
44isl
45iss
46ise
47is,
48is"
49ist
50iso
51isC
52iso
53isn
54iss
55isu
56ism
57ise
58isr
59is"
60is:
61ist
62isr
63isu
64ise
65is,
66is"
67ist
68iso
69isR
70ise
71ist
72isa
73isi
74isl
75ise
76isr
77is"
78is:
79ist
80isr
81isu
82ise
83is,
84is"
85ist
86isa
87isx
88isN
89isa
90ism
91ise
92is"
93is:
94is"
95is1
96is"
97is}
It seems to me that rather than treat it like a JSON object, it is handling as a string array. Any Inputs?
If the result is already JSON, then you don't want to use JSON.parse() since JSON.parse() converts a string representation of JSON into an object. Simply run your for loop as you coded and you should be able to get all the keys and their values.
However, if you do start out with a string representation of a JSON object, that's when you want to use JSON.parse().
//Starting with a JSON object
var result = {
"analgesicTax": false,
"unitPriceRequired": false,
"toConsumer": true,
"toRetailer": true,
"taxName": "1"
}
for (var prop in result) {
console.log(prop + " is " + result[prop]);
}
console.log('');
//Starting with JSON represented as a string
var result = "{\"analgesicTax\":false,\"unitPriceRequired\":false,\"toConsumer\":true,\"toRetailer\":true,\"taxName\":\"1\"}";
var data = JSON.parse(result);
for (var prop in data) {
console.log(prop + " is " + data[prop]);
}
try this.
var data = JSON.parse(result);
Object.keys(data).forEach(function (key) {
console.log(data[key]);
});
I have my JSON file like this:
{"companies":
[{"name":"LCBO", "City":"Mississauga", "Province":"Ontario",
"Website":"http://www.lcbo.com/content/lcbo/en.html#.WXtQ94jytPY",
"PhoneNumber":"1(800)668-5226",
"Longitude":"-79.381735", "Latitude":"43.648607"}]}
Here is my JavaScript to store the JSON file in local storage when the button is clicked:
$(document).ready(function() {
$('#btn1').click(function() {
$.ajax({
url:'company.json',
dataType:'json',
success: function(data) {
var u = data.companies[1];
$(u).each(function() {
$('#result1').append("<p>"+ "Company name: "+this.name + "<p>" +
"<p>"+ "City: " +this.City + "<p>" +
"<p>"+ "Province: "+this.Province + "<p>" +
"<p>"+ "Website: " +this.Website + "<p>" +
"<p>"+"Phone Number: "+this.PhoneNumber + "<p>" +
"<p>"+"Longitude: "+this.Longitude + "<p>" +
"<p>"+"Latitude: "+this.Latitude + "<p>");
saveData(u);
});
}
});
function saveData(data) {
var obj = {"Value":data};
if (window.localStorage) {
alert("Local Storage is supported");
localStorage.setItem("Information", JSON.stringify(obj));
} else {
alert("Local Storage is not supported");
}
}
});
The question is that how I get the value "Longitude" and "Latitude" from the local storage.
var info = JSON.parse(localStorage.getItem('Information'));
that way you'll get object stored in localStorage as a JSON object you can iterate through to get the values you want
You need to get the "Information" from localStorage, which will be a JSON string, parse it back into a javascrpt object, look in the "Value" property you created for the companies array and get an array element containing one company's data (the 0th is the first company returned from ajax), and then extract the Latitude (or Longiture) property.
JSON.parse(window.localStorage.get("Information")).Value.companies[0].Latitude
If this seems overly complicated, you can do it in steps:
var info = window.localStorage.get("Information");
var obj = JSON.parse(info);
var companies = obj.Value.companies;
var myCompany = companies[0];
var lat = myCompany.Latitute;
Also, perhaps simplify the data after ajax fetching instead of embedding it in another object. Also, the current structure will only cache the last-retrieved ajax query. To store multiple queries in localStorage requires either having a key for each company or pulling out the old object, updating it, and putting it back in localStorage. There is a limit as to what is practical to store locally.
I have a function that receives data from a previous JSON response, calls another web service, and adds the results from the second call to the end of the original JSON response. However, the items in my original array get replaced by items in the new array when I used extend. I understand that using $.extend will override my items with identical keys, but I cannot find another option as I am not trying to $.merge my items as I need to concatenate them. Is there any other viable option? Thanks!
//data is the object to which I am trying to add data
function verificaFileServer(data, subprograma, etapa, destino, lista, listaFileServer){
//checking whether some variable has been passed into the function
if(listaFileServer !== undefined){
//SharePoint REST Endpoint
var urlREST = "/_api/lists/getbytitle('File Server')/items?" +
"$select=Title,Link,Modified&$orderby=Modified desc&$filter=IDdoEvento eq " + subprograma + " and EtapaPAS eq '" + etapa + "' and TipodeArquivo eq '" + listaFileServer + "'";
$.ajax({
url: urlREST,
headers: { "Accept": "application/json; odata=verbose"},
success:function(dadosFileServer) {
//trying to add to the end of my original JSON object
$.extend(data.d.results,dadosFileServer.d.results);
//creating a new array containing the original and the new data
dadosConcatenados = data.d.results.sort(function(a, b) {
return (b["Modified"] > a["Modified"]) ? 1 : ((b["Modified"] < a["Modified"]) ? -1 : 0);
});
//calling a function that will build the output based on the concatenated array
montaSaida(dadosConcatenados, subprograma, etapa, lista, destino);
}
});
} else {
//calling a function that will build the output based on the original data
montaSaida(data, subprograma, etapa, lista, destino);
}
}
However, the items on the original array get replaced by items in the
new array.
Try using Array.prototype.concat()
var data = [1, 2, 3];
data = data.concat(4, 5, 6, 7, {"abc": [8, 9]});
console.log(data)
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: ''
}]