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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5295236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:41:30  来源:igfitidea点击:

Get json object by calling a URL with parameters

javascriptjqueryjsonmodel-view-controller

提问by EKet

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

我输入一个 URL,即 - 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.

而不是取回网页或其他东西,我想取回一个 json 对象,以便我可以在不同的页面上进行解析。

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.

我当然可以通过使用这些参数调用 MVC 控制器并返回一个 json 对象来实现这一点。但是,假设我需要在一个 js 文件中创建这个 json 对象,该文件从 URL 获取这些参数的值,然后我返回我的 json 作为结果。

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?

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

What is the proper/best way of handling this scenario, with MVC, js, jquery...anything??

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

Thanks a lot guys!

非常感谢伙计们!

采纳答案by EKet

Use jquery to parse the URL by inserting this into a <script>tag before creating the json object. from linkfrom LekisS

使用 jquery 通过<script>在创建 json 对象之前将其插入标签来解析 URL 。从链接从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.jsplugin to convert objects to JSON. So include this script also before the JSON object creation.

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

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.

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

Now we have everything inside a bunch of scripts but where do we get json object through URL calling?

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

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

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

www.mysite.com/getStuff?para1=value&para2=value2to get the json object.

www.mysite.com/getStuff?para1=value&para2=value2获取json对象。

回答by jordancpaul

You have a couple of options

你有几个选择

1) Generate the json in javascript

1)在javascript中生成json

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:

为此,您需要创建一个简单的页面,其中包含一个 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) Use an MVC framework

2)使用MVC框架

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).

现有的每个 MVC 框架都可以让您访问页面请求中使用的搜索参数。有些会要求您以 /function/arg1/arg2 样式提供它们(所以 /getStuff/jerry/engineer/12345,在您的情况下)。其他人使用更传统的 /function/?argName=argVal... 方法。一旦你有了参数,将它们以 JSON 格式 ( 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.

就我个人而言,我会使用 MVC 方法,因为它需要最少的运行来获得您想要的 JSON。但是,除非您熟悉 MVC 框架(例如蛋糕),否则您可能会发现启动和运行的过程有点艰巨——这些框架是为提供页面内容而设计的,但并不总是让它们提供 JSON清楚地记录在案。