I have a javascript object that I need to be able to pass to a web service via query string.
Say for example:
<script type="text/javascript">
var test = new Object();
test.date = new Date();
test.str = "hello world!";
test.list = new Array();
test.list.push('a');
test.list.push('b');
test.list.push('c');
</script>
Is there a way that I can serialize that object as JSON and then compress/encode it in some way that can be passed into a url's query string?
like:
var destination = 'http://mywebservice?'+encode(serialize(test));
$.get(destination, function(e)) { ... }
Thanks in advance
You want Douglas Crockford's json2.js: https://github.com/douglascrockford/JSON-js
var test = new Object();
test.date = new Date();
test.str = "hello world!";
var dest = 'http://mywebservice?'+encodeURIComponent( JSON.stringify(test) );
(oh, and don't use escape(), it's deprecated. Always use encodeURIComponent() instead)
But why not use a (session) cookie instead? Using the URI to pass data can be a major problem for SEO, for bookmarks, for links, etc.
You should remember that query string has maximum length (wiki said that it is 2083 chars), so you have to be carefully with putting there too large objects.
I think you just need jQuery post function:
http://api.jquery.com/jQuery.post/
It does perform a post of the data to the server. In my opinion a POST is better suited to send objects but I ignore the limitations you might have on the server.
Use the standard JSON stringify() method:
var destination = encodeURI('http://mywebservice?obj='+ JSON.stringify(test));
Related
I am trying to use JQuery to parse some JSON being sent back from an AJAX call. It appears to be failing to parse, and JSLint also says it's invalid JSON.
However, if I create the object directly, it works and I am able to loop through it - please see below:
var json = {layers:[{layer1:[17,16,15,14,12]}]}
alert(json)// <- This works and output object Object
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"
var parsing = JSON.parse(somestring)
alert(parsing) // <- this doesn't and breaks on parse
// The below code will work provided the parsing is commented out
json.layers.forEach(function (outerObj)
{
Object.keys(outerObj).forEach(function (key)
{
outerObj[key].forEach(function (item)
{
alert(item)
});
});
});
I'm struggling to wrap my head around why it won't parse, but appears to work.
Edit
I realise by wrapping quotes around layers and layer1 fixes it, just not sure why it works one way - but not the other.
there is a difference between javascript object and JSON object, all keys of JSON object must be quoted.
var somestring = "{layers:[{layer1:[17,16,15,14,12]}]}"// not a valid json to parse, it is a normal string, you can use JSON.stringify() to make it a valid json identifiable string.
so the correct JSON string will look like
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}';
var parsedJson = JSON.parse(somestring)
If you change sometring to some of the following examples, it will works.
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
var somestring = "{\"layers\":[{\"layer1\":[17,16,15,14,12]}]}"
The reason for this is, basically, that's how JSON was specified.
For further examples, take a look at w3schools
Best practice is to use JSON.stringify(Object) on one side, and JSON.parse(String) on the other. This will save you many hours of scratching your head over some niggling detail.
In your example, you could resolve the problem by
var somestring = JSON.stringify(json)
For future reference, however, JSON keys must be quoted, so your somestring should be written as:
var somestring = '{"layers":[{"layer1":[17,16,15,14,12]}]}'
Good luck!
Hey guys quick question what is the best approach on converting Model to Javascript.
I tried using this
#{
var arr = new string[3];
arr[0] = "1";
arr[1] = "2";
arr[2] = "3";
var jason = JsonConvert.SerializeObject(Model);
}
<script type="text/javascript">
var string = '#jason';
var variable2 = jQuery.parseJSON(string);
alert(variable2.Id);
</script>
as you can guess it did not work, I look through the sample of jQuery which should work but I am not sure if it is compatible with JsonConvert of .net
Its my first time on programming in the client side so this is quite a simple question but I tried looking the answer from the net. Mostly I see are uber complicated answers and at least 3 and higher old so I am guessing there should be an easier way to do this now?
I feel like this needs an answer because it's the number 2 result from google and has been viewed over 200 times, and as stated by the OP every other answer is generally long and/or convoluted. But the simplest answer is:
Javascript added to your aspx page:
<script type="text/javascript">
var myObject = <%=JsonConvert.SerializeObject(MyNetObject)%>;
</script>
The key bit being that your output of HTML looks as follows:
<script type="test/javascript">
var myObject = {"Prop1":"value1","Prop2":"Value2"};
</script>
Javascript natively handle JSON so you don't need to reparse anything on the client side. If the object is properly serialized it will be recognized without further conversion (this includes lists and object properties).
In the example provided in the OP the resultant Javascript object would be a simple array. So access to the elements on the client side would be:
alert(variable2[0]), alert(variable2[1]), alert(variable2[2])....
In order to provide the Javascript property calling functionality that OP is trying to do on the client side would require the following on the server side:
var json = JsonConvert.Serialize(new { ID1 = 1, ID2 = 2, ID3 = 3 });
In which an object with Named properties is serialized into the page.
I create an object in Javascript to pass as the argument to a PHP script.
var pattern = new Object();
pattern['#id'] = '';
pattern['#num'] = '';
pattern.cprop = new Object();
//pattern.aprop = new Object();
pattern['#id'] = id;
pattern['#num'] = pn;
pattern.cprop.$ = pb.find('input[name="subject"]').val() || '';
var json = {'pattern': pattern};
My Ajax call is
url: clr_url_base+'storepat.php?data='+encodeURIComponent($.toJSON(json))
In my PHP script, I use
$pat = json_decode(str_replace ('\"','"', $data), true);
$prep = $pat["pattern"]["#id"];
$sense = $pat["pattern"]["#num"];
$cprop = $pat["pattern"]["cprop"]["$"];
//$aprop = $pat["pattern"]["aprop"]["$"];
This works, but when I add the aprop value, it no longer works.All values are strings. Any suggestions as to what's going wrong.
Here are the two JSON strings:
{\"pattern\":{\"#id\":\"against\",\"#num\":\"1(1)\",\"cprop\":{\"$\":\"a person or thing (often abstract) opposed\"}}}
{\"pattern\":{\"#id\":\"against\",\"#num\":\"1(1)\",\"cprop\":{\"$\":\"a person or thing (often abstract) opposed\"},\"aprop\":{\"$\":\"verbs (to which \'against\' introduces idea of opposition); nouns denoting conflict\"}}}
The first has only has the value for cprop, while the second adds the value for aprop. Note that aprop has single-quotes. It is this kind of data that seems to beg for encoding in the Javascript and decoding in the PHP. The second bombs. I have some 20 fields from a form, so it would get quite complex to create the JSON by hand, rather than as fields in pattern. When the second bombs, the value of $pat is NULL.
I would strongly suggest POSTing the data via jQuery rather than passing in query string. Why? Because then you don't have to worry about URL encoding and such.
This may look like this in javascript/jQuery. Obviously the concept is basically the same for any sort of AJAX sending mechanism.
$.ajax({
type: 'POST',
url: clr_url_base+'storepat.php?',
contentType: 'application/json',
dataType: 'json', // if you expect JSON in return
data: json, // your JSON string here
success: // your success handler
error: // your error handler
});
On the PHP-side, since you are not dealing with form-encoded data, you would need to read PHP's raw input. Luckily this is very simple and converting the POST data into a PHP object/array is very trivial. It is as simple as this:
$json = file_get_contents('php://input');
$variable = json_decode($json);
You have a number of problems, but number one is that you have Magic Quotes enabled. That's why you have all those backslashes. Your crude attempt to "fix" it with str_replace is a bad idea, because there are other things besides " that gets escaped by Magic Quotes. You should find the setting in your php.ini file, and disable it. The same goes for "register globals", a very unsafe feature to be using. Reference $_GET['data'] instead.
With that out of the way, the next thing I would suggest is using POST instead of GET. This means you don't have to mess around with escaping data, as that always comes with the risk of screwing it up.
You should be able to implement these changes without too much trouble.
I'm using javascript and would like to take a URL string that I have and break it down into its components such as the host, path, and query arguments.
I need to do this in order to get to one of the query arguments, which is itself a URL and is thus encoded in the original URL string.
I feel like there should be an easy way to do this in Javascript. Perhaps something that looks like this:
var what_I_Want = url("http://www.domain.com?queryArg1=somequeryargument").getQueryArgumentValue("queryArg1");
The parseUri function will do everything you need
Edit
Alternatively you can get the DOM to do the hard work for you and access properties on a newly created a object for different parts of the URL.
<script type="text/javascript" language="javascript">
newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
</script>
Hope this will help..
In javascript you can do this by using split() for the params and using the location object for the protocol and domain -- like Carl suggested
Also you can use parseUri as Tak suggested
There is also a jQuery plugin which makes parsing easier if you are already using jQuery in your project: https://github.com/allmarkedup/jQuery-URL-Parser#readme
Example:
$.url('http://allmarkedup.com?sky=blue&grass=green').param('sky'); // returns 'blue'
Probably not the greatest way of doing it but a simple method to get the query string in JavaScript would be to just use something along the lines of:
a = "http://www.domain.com?queryArg1=somequeryargument";
query = a.substring(a.indexOf('?')+1);
You could then split the query up based on the &'s and again on the = to get at whatever param you need.
Sorry if this ain't very helpful as its a bit of a low tech method :P
EDIT:
Just wrote a quick little JavaScript object to get URL Query parameters for you (sort of like) in your example. Only tested it in chrome but in theory it should work :)
//Quick and dirty query Getter object.
function urlQueryGetter(url){
//array to store params
var qParam = new Array();
//function to get param
this.getParam = function(x){
return qParam[x];
}
//parse url
query = url.substring(url.indexOf('?')+1);
query_items = query.split('&');
for(i=0; i<query_items.length;i++){
s = query_items[i].split('=');
qParam[s[0]] = s[1];
}
}
//Useage
var bla = new urlQueryGetter("http://www.domain.com?queryArg1=somequeryargument&test=cheese");
alert(bla.getParam('test'));
i want to get hash parameters value in my java script
for example my url should be like that
www.example.com/#!mydata=data&myopt=option
i want to get mydata in variable which will be "data" as value,
and myopt "option"
iam trying to implement google ajax cowling like here
Google Code
and i have tried to implement jquery address
but with big fail so help me either by solving 1st part or give me simple walk through tutorial to implement jquery address to my ajax requests ,thank you
This piece of code will convert any well formed (i.e. properly url-encoded) request string into an object literal with values parsed.
var s = "#!mydata=data&myopt=option";
var o = {};
$.each(s.substr(2).split('&'), function(i, elem) {
var parts = elem.split('=');
o[parts[0]] = parts[1];
});
Then you can access values like o.myopt
UPDATE
Of course, to get the value from browser's address, you should use
var s = window.location.hash;