I have a json array being passed to a jade template.
This template then runs through the array adding rows to the html output.
However a new requirement no needs that json object to be passed to a javascript function, so I tried:
- var json = JSON.stringify(rows);
input.medium.success.button.error(type='submit', id='update_details', value= sendCommandLabel, onclick='sendCommand(' + json + ')')
which gives the following output (the full array omitted from brevity):
<input type="submit" id="update_details" value="Send Command" onclick="sendCommand([{"id":"id1;,"param1":value1, ... "}])">
Which is not useful as I am want to use this output in the javascript function and as it stands I can't consume it.
I am hoping I am missing something simple as my other option is to recreate the json array by looping through the objects in the renderer to recreate it!
UPDATE: I modified the code so instead of passing the array to the function, the array is hardcoded into the function while the jade page was being compiled. So this:
function sendStopCommandToAllSensors()
{
var hardcode = !{JSON.stringify(rows)};
became
function sendStopCommandToAllSensors()
{
var hardcode = [{"id":"id1", ... }, {"id":"id2", ... }];
But that still didn't work.
Puzzlingly adding a couple of simple alerts in there showed that there was the correct number of objects (later confirmed that there by cutting and pasting the resultant string directly into code and then manually adding a third object).
alert(hardcode.length); // displays 2
alert("rows: " + hardcode); // displays [object Object],[object Object]
Which is why in the loop that follows the
for (var row in hardcode)
{
alert("row: " + row); // displays 0 or 1, not an object
if (row.active == 1)
{
alert("Reached here"); // never reached
the final line is never reached.
UPDATE II: By stringifying hardcode I can output the human readable json.
alert("rows: " + JSON.stringify(hardcode));
Why is the code not seemingly parsing the array correctly and what to I do need to do correct it?
UPDATE III: I now having it working by using a two step traditional loop and assignment.
for (var i=0; i<rows.length; i++)
{
var row = rows[i];
So the question seems to be now, why didn't the for..in loop work as expected?
I am new to this, but I was going through similar problem I think.
But I am totally ok with JSON.stringify method, which was your first solution. It looks ugly in generated hmtl, but I found it useful in my case.
At least I think I understood it right and you are not trying to do some kind of magic what I can't absorb yet.
if
rows=[{id:id,param:param},{id:id2,param:param2}]
JADE:
- var json = JSON.stringify(rows);
input(type='submit', onclick='myFunction(' + json + ')')
JS:
function myFunction(myRows) {
console.log(myRows[0].id);
console.log(myRows[0].param);
console.log(myRows[1].id);
console.log(myRows[1].param);
.
.
at least it is ok in what I am working on.
I hope I didn't wrote pile of nonsense :)
Related
There's some weird issue it seems.
I'm trying to pass a php array to js, which I've accomplished. I can display the array size like so
document.getElementById("test").innerHTML = (jarr.length);
and it works perfectly fine, however, when I try to display a value in said array, it says object Object
and what's weird is if I go try to read a value which isnt stored, for example jarr[234] it says undefined because there's no value stored, so I know some data is being transferred.
Any help?
edit: here's how I passed the array to js
var jarr = <?php echo json_encode($testing); ?>;
edit: I forgot the remove the parse part before copying it, I was experimenting beforehand.
You should be able to just directly use jarr without parsing it, for example:
document.getElementById("test").innerHTML = jarr.length;
document.getElementById("first_element").innerHTML = jarr.length > 0 ? jarr[0] : "empty array";
If you are doing the above and the elements are showing up as object Object it means that inside your array, you are storing objects rather than primitive data types. So maybe try something like the following to generate a nice string representation of those objects (noting that this is needed for displaying them, but not for using them directly in your JavaScript code):
document.getElementById("first_element").innerHTML = jarr.length > 0 ? JSON.stringify(jarr[0]) : "empty array";
What Chris said fixed the issue!
"To show the entire array: document.getElementById("test").innerHTML = JSON.stringify(jarr); To show a single string: document.getElementById("test").innerHTML = jarr[0]; – Chris G 7 mins ago
"
For whatever reason adding the (stringify) fixes it for me.
An example
document.getElementById("test").innerHTML = JSON.stringify(jarr[2].title);
I'm looking for help in converting a particular elements in JSON message to an array using java script at run time. We wanted the script to be more generic. Actually we were trying the following which worked for single element and while changing it to handle for multiple elements at run time its not working.
//Working for Single element - Static
var bodyContext = JSON.parse(response.content)
if(bodyContext.companylist.company.constructor !== Array){
bodyContext.companylist.company = [bodyContext.companylist.company]
}
The above code works and converts Company in JSON message as a Array, Where as the below we tried for multiple elements is not working
//Not Working for multiple elements - dynamic
var bodyContext = JSON.parse(response.content)
var elementName = "";
//Loop runs every time and changes the value of elementName at every iteration
if(bodyContext.elementName .constructor !== Array){ //not working
bodyContext.elementName = [bodyContext.elementName] //Not working
}
instead of looking for "bodyContext.companylist.company" and converting into Array, "bodyContext.elementName" is checked and added to the bodycontext object.
how to handle this. ElementName variable along with JavaScript object is not recognized.
Please help.
you can JSON.parse(data) then you can fetch data from Javascript object like
$.each(Obj,function(key,value){
});
You'll want to use
bodyContext[elementName]
since
bodyContext.elementName
looks for a field in bodyContext named elementName, not the a field named after the value in elementName.
Also, you initialize elementName with "", and this won't match anything on the first iteration.
A javascript issue again, I can't understand the problem. I use Appinventor to transfer a message to an html file using webviewstring. the message sent is here, starting with 1%mc:
As you can see, it jumps to the next line because everyline has an \n at the end.
In javascript, I try to create an array of arrays using this code:
var wvdata = window.AppInventor.getWebViewString().split('\n');
var urlArray = [];
for (var i in wvdata){
urlArray.push(wvdata[i].split('%'));
}
I don't know what's wrong with it, since it was running fine when I splitted it with a ,. Just because I need to use comma in some places, I changed my splitters to % but this doesn't work. I use script blocks like this one to assign data inside the array to items, but now it just shows the default data, as if there were nothing inside urlArray.
document.getElementById("testname0").innerHTML = urlArray[0][2];
In an application I am working on I need to get a list of the names of all applicationScope variable then I need to cycle through them and filter out the ones starting with a know string say $xyx. I thought that the applicationScope.keySet().
I'm using this code for starter:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
if (itr.hasNext()){
var str:String = itr.next();
dBar.info(str,"Value = ");
}
if I put the variable col in a viewScope it shows a list of all the keys. but when I run the script the values displayed in the dBar info are not the keys but some other information that I'm not sure where it comes from.
I should just be able to iterat through the list of keys, am I missing something?
This code is in the before page loads event
After some poking around and experimenting I got this to work:
var col = applicationScope.keySet();
var itr:java.util.Iterator = col.iterator();
while (itr.hasNext()){
var str:Map.Entry = itr.next();
if (str.substring(0,9) == "$wfsLock_"){
//do stuff
}
}
so I'm now a happy camper.
Although your code works in SSJS, it is not correct (and that's why I don't like SSJS...).
The applicationScope is an implementation of the java.util.Map interface and the keySet() method returns a Set containing the keys in that Map. Every entry is (probably) a String (other data types like integers are actually also valid). The line
var str:Map.Entry = itr.next();
doesn't cast it to a Map.Entry: it doesn't really do anything: str remains a string.
The Map interface also has an entrySet() method that returns the entries (Map.Entry). You can use that to retrieve the key as well as the value:
var it = applicationScope.entrySet().iterator();
while (it.hasNext()) {
var entry = it.next();
print( entry.getKey() + " = " + entry.getValue() );
}
(in this code the print() line will use the toString() method of the key as well as the value to send information to the console)
I see from your code that you've installed my XPages Debug Toolbar. You can also use that to quickly check what's in the scopes and what the actual datatype is.
complete noob currently trying to complete a Uni assignment. We are creating a web app using HTML, css and JQuery. I've searched the web for an answer but can't quite figure out what I'm supposed to do.
I have set up a page where users can type in details for a shift, when they submit it, the data is pushed onto an array stored in localStorage using JSON stringify. That part works great and here it is:
var shift = {'location':$('#shift_location').val(), 'start_time':$('#shift_start_time').val(), 'end_time':$('#shift_end_time').val()};
var shift_list = JSON.parse(localStorage.shift);
shift_list.push(shift);
localStorage.shift = JSON.stringify(shift_list);
However I then need to take the last 'shift_location' 'shift_start_time' and 'shift_end_time' that has been added and stick it in a div on the page.
This is what I have come up with so far:
var result = JSON.parse(localStorage.shift);
$.each(result, function(k, v) {
$('.current_shift').text(k + ":" + v);
});
However, all that appears on the page is: 0:[object Object].
Any ideas on how to sort this out would be great. Like I said I'm a complete noob and this is my first time posting on here so apologies in advance if I've missed out any important bits of code or framed the question incorrectly.
Thanks
James
You have an array of objects, you have to get the last object in the array first :
var result = JSON.parse(localStorage.getItem('shift'));
var obj = result.pop();
$('.current_shift').text(obj.start_time + ":" + obj.end_time);
This is an Array shift_list.
So it looks like locationStorage.shift is an array. That is why the k is an integer. Try this:
$.each(result, function(k, v) {
$('.current_shift').text(v.location);
});
You will see that it is an object since your shift is stored in Objects. For debugging you can do this:
$.each(result, function(k, v) {
console.log(v);
$('.current_shift').text(v.location);
});
Open Chrome, and look at the console, there you will see your objects.