Get json object by calling a URL with parameters - javascript

This seems like a simple problem but I have a coder's mental block:
The concept:
I type a URL, i.e - www.mysite.com/getStuff?name=Jerry&occupation=Engineer&Id=12345
and instead of getting back a webpage or something I want to get back a json object so that I can parse on a different page.
The catch:
I can certainly accomplish this by calling a MVC controller with those parameters and returning a json object. However, Let's say I need to create this json object inside a js file that takes those parameters' values from the URL and I get my json back as the result.
The questions
Can I pass parameters to a js file and return a json object? Or
Can I call a js file from a controller and pass it these parameters to and retrieve a json object?
Do I even need to call a controller via a URL, or can I just call a js file giving it parameters from a URL and then returning the json?
What is the proper/best way of handling this scenario, with MVC, js, jquery...anything??
Thanks a lot guys!

You have a couple of options
1) Generate the json in javascript
To do this you will need to create a simple page which includes a javascript JSON encoder (such as https://github.com/douglascrockford/JSON-js). This would be hosted at "/getStuff/index.html" and would be called by typing "www.mysite.com/getStuff/?arg=val..." For example:
<html>
<head>
<script src="json.js" type="text/javascript"></script>
<script type="text/javascript">
//this function will take the window.location.search string of ?name=val and
//create an object like {'name':'val'}
var parseUrl = function(urlParams) {
var retObj = {};
var urlParameters = null;
if (!urlParams || urlParams.length == 0) {return retObj}
if (urlParams.charAt(0) == '?') {
urlParameters = urlParams.substring(1);
}else {
urlParameters = urlParams;
}
if (urlParameters.length == 0) {return retObj}
var parameterPairs = urlParameters.split('&');
var x;
for (x in parameterPairs) {
var parameterPair = parameterPairs[x];
parameterPair = parameterPair.split('=');
retObj[parameterPair[0]] = parameterPair[1];
}
return retObj;
};
var createJson = function(){
var params = parseUrl(window.location.search);
//do work here
var retObj = {}; //suppose this is the result of the work
document.print(JSON.stringify(retObj)); //use the included JSON encoder
};
</script>
</head>
<body onload="createJson();">
</body>
</html>
2) Use an MVC framework
Every MVC framework in existance will give you access to the search params used in the page request. Some will require you to provide them in /function/arg1/arg2 style (so /getStuff/jerry/engineer/12345, in your case). Others use a more traditional /function/?argName=argVal... approach. Once you have the arguments, it is a trivial matter to write them to the page in JSON format (http://php.net/manual/en/book.json.php).
Decisions, Decisions
Personally, I would use the MVC method, as it requires the least running around to get the JSON you want. However, unless you are familiar with an MVC framework (such as cake) you will probably find the process of getting up and running to be a bit arduous - these frameworks are designed for serving page content and getting them to serve up JSON is not always clearly documented.

Use jquery to parse the URL by inserting this into a <script> tag before creating the json object. from link from LekisS
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
// Get object of URL parameters
var allVars = $.getUrlVars();
// Getting URL var by its nam
var byName = $.getUrlVar('name');
In a separate script tag create your json object. You will need to include the Json2.js plugin to convert objects to JSON. So include this script also before the JSON object creation.
Once you have the appropriate scripts and variables you can create a json object using those parameters as needed by calling them as shown at the bottom of the example using jquery. You can also look up which JSON conversion (i.e, to string or object) you want from the Json2.js script file.
Now we have everything inside a bunch of scripts but where do we get json object through URL calling?
So the answer is simple:
Create a simple html page with these scripts where the last script finally creates and returns the json. Upload to server and use URL parameters like
www.mysite.com/getStuff?para1=value&para2=value2 to get the json object.

Related

Accessing a Javascript variable inside an HTML file

I'm doing a little bit of reverse engineering on the Rapportive API in Gmail.
I make this request
import requests
url ='https://api.linkedin.com/uas/js/xdrpc.html'
r = requests.get(url)
print r.text
The response is an empty HTML file that has a lot of Javascript in it. On line 3661, it sets the RequestHeader for the subsequent call to Rapportive:
ak.setRequestHeader("oauth_token", ae);
Is there a way I can request that page and then return ae?
I think you can try:
Get the page as you already does;
Remove all non-javascript elements from the response page;
Prepend a javascript (described below) in the page's javascript to override some code;
Execute it with eval('<code>');
Check if the token has been set correctly;
I'm proposing the following code to override the XMLHttpRequest.setRequestHeader functionality to be able to get the token:
// this will keep the token
var headerToken;
// create a backup method
XMLHttpRequest.prototype.setRequestHeaderBkp =
XMLHttpRequest.prototype.setRequestHeader;
// override the "setRequestHeader" method
XMLHttpRequest.prototype.setRequestHeader = function(key, val)
{
if ('oauth_token' === key)
headerToken = val;
this.setRequestHeaderBkp(key, val);
}
If you are just interested in retrieving the token can't you just do a regex match:
var str = '<script>var a = 1;...ak.setRequestHeader("oauth_token", ae);...</script>';
var token = str.match(/setRequestHeader\("oauth_token",\s*([^)]+)/)[1];
Although this assumes ae is the actual string value. If it's a variable this approach wouldn't work as easily.
Edit: If it's a variable you could do something like:
str.replace(/\w+\.setRequestHeader\([^,]+,\s*([^)]+)\s*\);/, 'oauthToken = \1';
Before running the JavaScript returned from the page, then the global oauthToken (notice the missing 'var') will contain the value of the token, assuming the the evaluation of the code is run in the same scope as the caller.

Sending and getting data via $.load jquery

I'm writing a system in HTML5 and Javascript, using a webservice to get data in database.
I have just one page, the index.html, the other pages i load in a <div>
The thing is, i have one page to edit and add new users.
When a load this page for add new user, i do this:
$("#box-content").load("views/motorista_add.html");
But, i want send a parameter or something else, to tell to 'motorista_add.html' load data from webservice to edit an user. I've tried this:
$("#box-content").load("views/motorista_add.html?id=1");
And i try to get using this:
function getUrlVar(key) {
var re = new RegExp('(?:\\?|&)' + key + '=(.*?)(?=&|$)', 'gi');
var r = [], m;
while ((m = re.exec(document.location.search)) != null)
r.push(m[1]);
return r;
}
But don't work.
Have i an way to do this without use PHP?
This won't work. Suppose your are loading the motorista_add.html in a page index.html. Then the JS code, the function getUrlVar(), will execute on the page index.html. So document.location that the function will get won't be motorista_add.html but index.html.
So Yes. To do the stuff you are intending, you need server side language, like PHP. Now, on the server side, you get the id parameter via GET variable and use it to build up your motorista_add.php.
You can pass data this way:
$("#box-content").load("views/motorista_add.html", { id : 1 });
Note: The POST method is used if data is provided as an object (like the example above); otherwise, GET is assumed. More info: https://api.jquery.com/load/

How to load JSON data in Cocos2d-X 3.0 in javascript

How would one load a javascript structure (object or array) from a file in Cocos2d-X 3.
My res/test.json:
{
version:"1.0",
data:"this is some data."
}
I'm able to load the file content like so:
var data = fileUtil.getStringFromFile('res/test.json');
cc.log(data);
What is the best way to load the javascript structure from the string? Is there a function in cocos2d-x to do this directly?
The "standard" JSON.parse works:
var fileUtil = cc.FileUtils.getInstance();
var data = fileUtil.getStringFromFile('res/test.json');
var jData = JSON.parse(data);
But note all attribute names must be passed in quotes, otherwise the parser will fail. res/test.json must then look like this:
{
"version":"1.0",
"data":"this is some data."
}

How can I create web service functionality via html and JavaScript

I want write a page that returns nothing but reads the parameters posted to it and manipulate them (via JavaScript) before similarly posting to third party's page. Anything returned from the third party will be dropped on the floor. Basically, I'm looking to create a proxy. My 'middle' page will need to run JavaScript. The end page will post to the middle page but not leave the page or report the status of the post.
You'll need to pass the values to your proxy using the GET form method and use window.location.search to get the values (this will only work with simple values, not file uploads).
var qsParm = new Array();
function qs() {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0) {
var key = parms[i].substring(0,pos);
var val = parms[i].substring(pos+1);
qsParm[key] = val;
}
}
}
javascript.about.com article on query passing
To resend you'll need to create and populate a form and them call the submit() method on the form element.

Passing data without using cookies in Javascript

Is there a way to pass data between pages without using cookies and a server-side language in javascript? every way I found incorporates cookies or a server-side language (PHP session vars).
You can pass it through a query string.
This link will give you the code to get it using JavaScript.
http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
code snippet from the page:
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
You can always add data to the url query string when you navigate, like:
/site/page2?username=foo&bar=110
Of course you have to recognize that users can manipulate those values so some kind of validation will still be necessary when the new page loads and uses those values.

Categories

Resources