I'm trying to take a URL's hash value, send it through a function, turn that value into an object, but ultimately send the value to JSON. I have the following setup:
function content(cur){
var mycur = $H(cur);
var pars = "p="+mycur.toJSON();
new Ajax.Updater('my_box', 'test.php', {
parameters: pars
});
}
function update(){
if(window.location.hash.length > 0){
content(window.location.hash.substr(1)); // Everything after the '#'
}
}
var curHashVal = window.location.hash;
window.onload = function(){
setInterval(function(){
if(curHashVal != window.location.hash){
update();
curHashVal = window.location.hash;
}
},1);
}
But for some reason, I can't seem to get the right JSON output. It will either return as a very large object (1:"{",2:"k") or not return at all. I doubt that it is impossible to accomplish, but I've exhausted most of the ways I can think of.
Other ways I've tried were "{" + cur + "}" as well as cur.toObject(), however, none seemed to get the job done.
Thanks for the help!
EDIT: As an end result, I'd like the URL (say product:3,confirmed:1) to be returned as {"product":3,"confirmed":1}
A typical implementation of toJSON() needs either an Array or an Object as the top-most element. Sonsomethig like this will probably work:
var pars = {p: myCur};
pars = pars.toJSON();
First of all native JSON support and the toJSONmethod is not available in all browsers. Older browsers like IE 6/7 or Firefox 2/3 do not support it. You should use a JSON library like json2 by Douglas Crockford. Second I would suggest to use the stringify method of the global JSON object instead of the toJSON function. In my tests
JSON.stringify("...")
works just fine.
If anyone is still looking for my answer, here's the solution!
function build_json(str){
var new_str = "{";
var cut = str.split(",");
for(var x=0; x < cut.length; x++){
if(x > 0){new_str = new_str+",";}
var s = cut[x].split(":");
new_str = new_str+"\""+s[0]+"\":\""+s[1]+"\"";
}
return new_str+"}";
}
Related
I realized how bad I am with javascript :(
I have this:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
});
return vars;
}
var theidis = getUrlVars()["id"];
and
$.tzPOST = function(action,data,callback){
$.post('php/ajax.php?id='+theidis,'&action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?id='+theidis,'&action='+action,data,callback,'json');
}
The first gets the ?id=value parameter properly. I tested with an alert(theidis).
I am looking to do a simple thing - sorry if this is stupid -.- I have worked as this for so long that I am beginning to oversee things.
I want an ?id=value to be added to the php/ajax.php. I tried with the above, but it doesn't seem to work. I also tried by just adding it.
Thank you in advance. :-)
Your $.get call specifies
'php/ajax.php?id='+theidis, '&action='+action, data ...
It looks like you're passing data twice. Either &action='+action should be your data parameter, or data. Did you mean to concatenate the &action part into the URL?
you probably meant:
$.tzGET = function(action,data,callback){
$.get('php/ajax.php?id='+theidis + '&action='+action,data,callback,'json');
}
Change the , sign to + sign.
NOTE!: data should be null if you are cocncating string to the URL's query string.
URl.Action is generating a query string in a way that works on IE8, but not on Chrome when a date is being passed.
Here is our code.
function RunReport( PdfOrExcel)
{
var ChartType = "Pdf";
var argCounter = 0;
linkUrl = '#Url.Action("ClassAssignmentLoadSummaryReport", "ReportsScheduling", new { PdfOrExcel="[1]", RptDate="[2]" } )';
var objToSend = new Object();
value = $('#RptDate').val()
dataToSend.RptDate =value;
linkUrl = linkUrl.replace("%5B1%5D", PdfOrExcel);
linkUrl = linkUrl.replace("%5B2%5D", value );
w = window.open(linkurl);
w.focus();
}
(this is a little ugly becuase we unwound several function to get the code above)
It generates a url like this:
/appName/ReportsScheduling/ClassAssignmentLoadSummaryReport?PdfOrExcel=Pdf&RptDate=8/6/2012
If we change it like this it works in Chrome just fine.
/appName/ReportsScheduling/ClassAssignmentLoadSummaryReport?PdfOrExcel=Pdf&RptDate=8/6/2012
I assume we are doing something dumb and it's generating it this way because of that, but I can't figure out what We're doing wrong.
Any help is greatly appreciated.
It looks like your string is getting encoded. Try wrapping the Url.Action() call with #Html.Raw().
If it's really getting that messy..
Why not just use..
var href = "/ReportsScheduling/ClassAssignmentLoadSummaryReport?PdfOrExcel=blah&RptDate=blahDate"
/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}
suppose I have a function:
function getLayerInfo(uuid, top, left, index, pindex) {
this.uuid = uuid;
this.top = top;
this.left = left;
this.index = index;
this.pindex = pindex;
}
then I use json menthod in json.js:
var layer = new getLayerInfo('abc', 123, 456, 4, 5);
var layerjson = layer.toJSONString();
console.log(layerjson );
It have show the correct result,
So if I want restore the json to array or something else,or what should I do?
Or what I want is just need the "index" property value?
What should I do?
Thank you
If your using jQuery do this:
var result = $.parseJSON(layerjson);
jQuery is recommended because it will use the best and fastest method to parse the JSON string (First trying to run browser parser and then, if unavailable, javascript/built in parsers)
if not using jQuery just run this (it uses browser parser, but be careful with older browsers, make sure it exists):
var result = JSON.parse(layerjson);
Try using JSON.parse on your layerjson variable:
var obj = JSON.parse(layerjson);
alert(obj.index);
Use .parseJSON() method to convert the string back to object.
var layerObj = layerJSON.parseJSON();
layerObj.index will give you the value of the property.
I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}
EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'
If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.
To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"
Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.
Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.
Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...