admin管理员组文章数量:1291123
This seems like a simple problem but I have a coder's mental block:
The concept:
I type a URL, i.e - www.mysite/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 acplish 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!
This seems like a simple problem but I have a coder's mental block:
The concept:
I type a URL, i.e - www.mysite./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 acplish 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!
Share Improve this question asked Mar 14, 2011 at 5:55 EKetEKet 7,31415 gold badges53 silver badges72 bronze badges 7- As long as you can return a JSON objet, you can call the file you want. The only problem with Javascript is to get your values from the URL. You'll need to write a GET function to get them where PHP just needs a $_GET. – Thomas Menga Commented Mar 14, 2011 at 6:38
- It's difficult to understand what you are trying to acheive.. – Jishnu A P Commented Mar 14, 2011 at 6:39
- @LekisS, thanks I do see what you're saying. @TheSuperTramp, it is difficult to understand what you don't understand because you didn't explain what does not make sense and why....because legibly, what I'm trying to achieve is clearly stated in the title and the body. Perhaps the "how" and "why" is unclear but I'll need more than "I don't understand" to help you. – EKet Commented Mar 14, 2011 at 7:15
- @EKet: are you ok with my answer ? Or do you need extra informations ? – Thomas Menga Commented Mar 14, 2011 at 7:16
- @LekisS: Yes I understand the concept of what you're saying, js doesn't have a get method so I'll have to parse url's for my parameters. But I'm not sure how I will actually call the file I want in practice to get my json object. Do I just call it in the url? An example would be appreciated or some elaboration. Thanks a lot! – EKet Commented Mar 14, 2011 at 7:19
2 Answers
Reset to default 2You 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./douglascrockford/JSON-js). This would be hosted at "/getStuff/index.html" and would be called by typing "www.mysite./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/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./getStuff?para1=value¶2=value2
to get the json object.
本文标签: javascriptGet json object by calling a URL with parametersStack Overflow
版权声明:本文标题:javascript - Get json object by calling a URL with parameters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741518155a2383019.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论