通过调用带参数的URL获取json对象

发布于 2024-10-22 05:02:22 字数 580 浏览 1 评论 0原文

这似乎是一个简单的问题,但我有一个编码员的心理障碍:

概念:

我输入一个 URL,即 - www.mysite.com/getStuff?name=Jerry&ocupation=Engineer&Id=12345

我不想返回网页或其他内容,而是想返回 json 对象,以便可以在不同的页面上进行解析。

问题:

我当然可以通过使用这些参数调用 MVC 控制器并返回 json 对象来完成此任务。然而,假设我需要在 js 文件中创建这个 json 对象,该文件从 URL 中获取这些参数的值,然后我将 json 作为结果返回。

问题

我可以将参数传递给js文件并返回json对象吗?或者 我可以从控制器调用 js 文件并将这些参数传递给它并检索 json 对象吗?
我是否需要通过 URL 调用控制器,或者我可以只调用 js 文件,从 URL 中为其提供参数,然后返回 json?

使用 MVC、js、jquery...处理这种情况的正确/最佳方法是什么?

非常感谢大家!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疧_╮線 2024-10-29 05:02:22

您有几个选项

1) 在 javascript 中生成 json

为此,您需要创建一个简单的页面,其中包含 javascript JSON 编码器(例如 https://github.com/douglascrockford/JSON-js)。这将托管在“/getStuff/index.html”,并通过键入“www.mysite.com/getStuff/?arg=val...”来调用,例如:

<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) 使用 MVC 框架

的每个 MVC 框架都将允许您访问页面请求中使用的搜索参数。有些会要求您以 /function/arg1/arg2 样式提供它们(在您的情况下是 /getStuff/jerry/engineer/12345 )。其他人使用更传统的 /function/?argName=argVal... 方法。一旦有了参数,将它们以 JSON 格式写入页面就很简单了( http://php.net/manual/en/book.json.php)。

决策,决策

就个人而言,我会使用 MVC 方法,因为它需要最少的运行才能获得您想要的 JSON。但是,除非您熟悉 MVC 框架(例如 cake),否则您可能会发现启动和运行的过程有点困难 - 这些框架是为提供页面内容而设计的,但并不总是让它们提供 JSON明确记录。

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.

拥有 2024-10-29 05:02:22

在创建 json 对象之前,通过将其插入到

$.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');

一个单独的脚本标签创建您的 json 对象。您需要包含 Json2.js 插件才能将对象转换为 JSON。因此,在创建 JSON 对象之前也包含此脚本。

一旦有了适当的脚本和变量,您就可以根据需要使用这些参数创建一个 json 对象,方法是使用 jquery 调用它们,如示例底部所示。您还可以从 Json2.js 脚本文件中查找所需的 JSON 转换(即字符串或对象)。

现在我们在一堆脚本中拥有了所有内容,但是我们从哪里通过 URL 调用获取 json 对象呢?

所以答案很简单:

使用这些脚本创建一个简单的 html 页面,其中最后一个脚本最终创建并返回 json。上传到服务器并使用

www.mysite.com/getStuff?para1=value¶2=value2 等 URL 参数获取 json 对象。

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¶2=value2 to get the json object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文