I have this Javascript data:
[{id:123,type:"test"},{id:154,type:"another"}]
How would you transform that into something so that I can pass it as a HTTP post request?
menu[0][id] = 123
menu[0][type] = test
menu[1][id] = 154
menu[1][type] = another
I dont want to pass the actual JSON data, I want to clean it up and pass it as formatted HTTP paramaters.
EDIT
Was able to parse the object on the client side using something like this, maybe you guys would suggest something better before I sign this as "answered"?
this.serialize = function(elem) {
var childs = elem.childElements();
var str = "";
for(var i=0, item; i<childs.length; i++) {
item = childs[i];
str += ((i)?"&":"")+"menu[" + i +"][id]=" + item.id.replace(/item_/,"");
str += "&menu[" + i +"][type]=" + item.className;
str += "&menu[" + i +"][section]=" + elem.id;
str += "&menu[" + i +"][position]=" + i;
}
return str;
}
var data = [{id:123,type:"test"},{id:154,type:"another"}];
var params = new Array();
for(var x = 0; x < data.length; x++) {
params.push("id=[" + x + "]=" + escape(data[x].id));
params.push("type=[" + x + "]=" + escape(data[x].type));
}
alert(params.join("&")); // output: id=[0]=123&type=[0]=test&id=[1]=154&type=[1]=another
Is that what you want?
menu0.id=123&menu0.type=test&menu1.id=154&menu1.type=another
This is fairly easy to parse on the server, in that it's a regular format.
I believe HTTP POST only accepts a flat key/value collection, not any arbitrary JavaScript data structure.
If you can flatten it (for example, like John Stauffer shows), and if you're posting to your own domain, you can use an XMLHttpRequest to post and pass the key/value collection, formatted like a query string, with the .send(data) method.
If you don't want to implement it yourself most JavaScript libraries should have an implementation (e.g. jQuery.post).
"?qsparam=" + escape("[{id:123,type:'test'},{id:154,type:'another'},...]")
Related
I"m attempting to build a string in order to put the results in a DataTables table.
I'm taking an array and using regex to get everything in it's own index and my resultant string array is this:
["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"]
One big string array with everything in its own index. Next I'm using a loop and building a string in order to pass it to a datatables table. The result of which SHOULD look like this:
var dataString = [
["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Instead I'm getting this:
var dataString = undefined["41.8059016", "-77.0727825", "School Zone"],
["41.804526", "-77.075572", "Something"],
["41.804398", "-77.0743704", "Some Other Thing"],
["41.8073731", "-77.07304", "Pedestrian"]
];
Here is my loop code to build the string from the array:
for(var i = 0; i < routePoints.length-3; i+=3){
console.log(routePoints);
if(i >= 0 && i < routePoints.length - 4){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"],';
}else if(i == routePoints.length - 3){
dataSetString += '["' + routePoints[i] + '", "' + routePoints[i + 1] + '", "' + routePoints[i + 2] + '"]';
}
}
If I simply deleted the "undefined" and paste the code in, the datatabe populates fine, but I cannot see where the undefined is even coming from. Thanks for the second set of eyes!
Usually, the undefined comes from your initialization. I don't see the code here, but you probably have something like:
var dataSetString;
instead, you should always start an empty string as:
var dataSetString = "";
As to why this happens. All uninitialized variables default to undefined. When you use the += operation, it will try to interpret what your are doing (if you have two numbers it will add them, two strings: concatenate). Undefined has no good += operation, so it uses the second part of the operation the string you are passing in. So, it automatically converts the undefined to a string and concatenates the new string to it, ending up with "undefined[blah,blah,blah"
You shouldn't compose a String like that.
It doesn't look like you need a string anyway but a 2D array.
var data = ["41.8059016", "-77.0727825", "School Zone",
"41.804526", "-77.075572", "Something",
"41.804398", "-77.0743704", "Some Other Thing",
"41.8073731", "-77.07304", "Pedestrian"
];
var dataString = [];
for (var i = 0; i < data.length; i+=3) dataString.push(data.slice(i, i + 3));
console.log(dataString);
// Should you actually need a string, you can use JSON.stringify()
console.log(JSON.stringify(dataString));
I have a Problem with my push function in JavaScript.
<script type="text/javascript">
var myArr = []
var len = myArr.length
$.getJSON('daten.json', function(data) {
$.each(data,function(key,value) {
for(var i = 0; i <= len; i++){
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
}
})
$('.content').html(myArr.join(''))
})
</script>
I need to convert value.Name+i like this = value.Name0, value.Name1 and so on. I got a JSON File and the Keys are Dynamic, so the first entry got Name0 the second Name1 and so on. Now I must print the JSON file on my html page, but how I can write this line:
myArr.push("<p>" + value.Name+i ," ", value.Nachname+i + "</p>")
with my var i which increment in the loop, to call the Keys in my JSON file?
Like value.Name0. Doing value.Name+i and value.Name.i does not work.
It seems to me what you're looking for is something like this:
myArr.push("<p>" + value['Name'+i] ," ", value['Nachname'+i] + "</p>")
This portion of javascript is covered pretty nicely here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Take the object property in a variable, use condition to check if it has value or not then concat it
var nameval = value.name;
then use in your javascript variable
nameval+i
You need to convert your i (integer value) to string prior to adding it.
use:
value.Name + i.toString()
here's the jfiddle link: http://jsfiddle.net/kpqmp49o/
I have dropDown element which takes the options in the format
ctrlOptions:{0:'String',1:'int'}
in addition to simple data types i have user defined data types hence i want to populate this dynamicaly . so i used a loop and concatenation
var dropDown = "{"
for(var i=0;i<dataTypesList.length;i++){
if(i == dataTypesList.length-1){
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name + "'}";
}else{
dropDown = dropDown + i + ":" + "'" + dataTypesList[i].Name+ "'" + ",";
}}
This yields be the options in required format but along with quotes around it like
ctrlOptions:"{0:'String',1:'int'}"
i want to remove the double quotes i tried with replace it diesnt seem to help. how can i achieve this can i use any other way.
What you want to create is an object & not a string.
So wildly guessing from your code, that the input dataTypesList looks something like this:
dataTypesList = [{Name:'String'}, {Name:'int'}]
You should use :
var dropDown = {};
for(var i=0;i<dataTypesList.length;i++)
dropDown[i] = dataTypesList[i].Name;
And then Output is an object :
{0: "String", 1: "int"}
you can use JSON.parse to convert the options string from string json to object json:
Using your code (slightly modified):
var dropDown = "{"
for(var i = 0; i < dataTypesList.length; i++)
{
if(i === dataTypesList.length - 1)
{
dropDown += i + ":'" + dataTypesList[i].Name + "'}";
}
else
{
dropDown += i + ":'" + dataTypesList[i].Name + "',";
}
}
// later...
ctrlOptions: JSON.parse(dropDown);
Verify your target browsers are compatible: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If not, there are some libraries compatible with older browsers that do the same thing. JSON2 is recommended by the author for out-of-date browsers: https://github.com/douglascrockford/JSON-js
I'm having trouble with JS .split() method in a GAS script. I copy and paste the headers of other google sheet as variable headers (the usual way will be copy and paste). This pasted selection contains some empty and undefined elements. I need to turn this elements in an array. So I split it and use the .filterto clean empty elements. But, when I run the script, the var arrayHeaders remains equal to headers, as if the .split(" ") didn't make any change, this way:
This is my code:
var headers = "STUDENT Parentage GRADE YEAR DATE GUIDE";
var arrayHeaders = headers.split(" ");
// arrayHeaders = arrayHeaders.filter(function(n){return n});
Logger.log("headers = " + headers);
Logger.log("arrayHeaders = " + arrayHeaders);
Logger.log("arrayHeaders length " + arrayHeaders.length);
for (var i = 0; i < arrayHeaders.length; i++){
var NOME_Cell = sheet.getRange(1, i +1);
Logger.log("NOME_Cell" + NOME_Cell);
Logger.log("arrayHeaders[i]" + arrayHeaders[i]);
NOME_Cell.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
}
If I delete all spaces after paste the string and press space again, then the .split(" ") works well.
Before asking this question, I read this other one, but I'm still stucked with what is going wrong here.
Thanks in advance for any help!
I'm pretty sure your headers variable is not a String. Try this:
var arrayHeaders = headers.toString().split(/[\s\t]+/);
When you are performing split(""), make sure the words in the string are seperated by samething which are passing to .split() method.
Your arrayHeaders is same as the headers.
var headers = "STUDENT Parentage GRADE YEAR DATE GUIDE";
var arrayHeaders = headers.split(" ");
// arrayHeaders = arrayHeaders.filter(function(n){return n});
Logger.log("headers = " + headers);
Logger.log("arrayHeaders = " + arrayHeaders);
Logger.log("arrayHeaders length " + arrayHeaders.length);
for (var i = 0; i < arrayHeaders.length; i++){
var NOME_Cell = sheet.getRange(1, i +1);
Logger.log("NOME_Cell" + NOME_Cell);
Logger.log("arrayHeaders[i]" + arrayHeaders[i]);
NOME_Cell.setValue(arrayHeaders[i]).setBackgroundRGB(34, 139, 34).setFontSize(font_size).setFontWeight("bold").setFontFamily("Arial");
}
Here i think, the seperation of header is not same. make sure the seperation of headers are of one space or two spaces or three spaces..
I would like to make a small gadget to use at work and show me the time of check in, from the morning.
I am trying to open a network file using http protocol and read from it the line which is referring to my check in.
This is located on our intranet and can be accessed like this:
filename = 'http://www.intranet.loc/docs/dru/Acces/' + ystr + '-' + mstr + '-' + dstr + '.mvm';
Every employer has a unique code for check in. The structure of the check In file is like this:
12:475663:1306285:072819:11:1:1:0:
12:512362:1306285:072837:11:1:1:0:
12:392058:1306285:072927:11:1:1:0:
12:516990:1306285:072947:11:1:1:0:
12:288789:1306285:073018:11:1:1:0:
12:510353:1306285:073032:11:1:1:0:
12:453338:1306285:073033:11:1:1:0:
12:510364:1306285:073153:11:1:1:0:
12:510640:1306285:073156:11:1:1:0:
In this example, 12 is the gate number, which I don't need, the second is my ID, the third is the current date, and what I need is the fourth (the hour).
Edit:
I am using this function to return the content of the mvm file with no luck:
function readfile(fileToRead) {
var allText = [];
var allTextLines = [];
var Lines = [];
var Cells = [];
var txtFile = new XMLHttpRequest();
txtFile.open("GET",fileToRead, true);
allText = txtFile.responseText;
allTextLines = allText.split(/r\r\n|\n/);
return allTextLines;
}
Do you really need a RegEx? Would it be possible to split the line by ":"?
$.get('http://www.intranet.loc/docs/dru/Acces/' + ystr + '-' + mstr + '-' + dstr + '.mvm', function(data) {
var lines = data.split("\n"),
values;
for (var i in lines) {
values = lines[i].split(':');
}
});
With this you would have everything you need.