繁体   English   中英

在没有服务器端脚本的情况下将JSON本地加载到JavaScript变量中?

[英]Loading JSON into JavaScript variable locally without server-side script?

我有41个JSON对象,每个对象具有相同的方案。

这些对象相当大,因此,当从idmyPicker<select>菜单中选择<option>时,我想将对象有条件地加载到JavaScript脚本中。

到目前为止,我已经设置了jQuery来处理<select>上的更改:

$('#myPicker').change(function() {
    alert('Value change to ' + $(this).attr('value'));
    $('#container').empty();
    init();
});

函数init()div内容绘制为container

当我更改myPicker ,我希望init()的行为类似于init(value) ,这又告诉init从文件中加载41个JSON对象之一(基于value )。

在这种情况下,是否可以从文件(位于服务器端)加载一大块JSON,还是我需要使用服务器端脚本来处理Ajax表单提交和响应等?

编辑

我写了以下代码:

<script language="javascript" type="text/javascript">

     $(document).ready(function(){
        $('#cellTypePicker').change(function() {
            alert('Value change to ' + $(this).attr('value'));
            $('#container').empty();
            initFromPicker($(this).attr('value'));
        });
     });

     function initFromPicker(name) {
        // pick default cell type from picker, if name is undefined
        if (typeof name === "undefined")
            name = 'AG10803-DS12374';
        var jsonUrl = "file://foo/bar/results/json/" + name + ".json";
        alert(jsonUrl);
        $.ajax({
            url: jsonUrl,
            dataType: 'json',
            success: function(response){
                alert("Success!");
            },
            error: function(xhr, textStatus, errorThrown){
                alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
            }
        });
        init(); // refills container...
     }
</script>

<body onload="initFromPicker();">
...

alert("Success!"); 永远不会被打电话。

相反,我收到以下错误:

Error: error | Error: NETWORK_ERR: XMLHttpRequest Exception 101 | [object Object]

我正在检查值jsonUrl ,它似乎是一个正确的URL。 它指向的文件存在,并且我有权访问它(它位于我的主文件夹中)。 我还有什么想念的吗?

让我确保我了解您的问题。 我想您要:

  1. 那里有一些包含JSON对象的文件
  2. 根据选择哪个选项,加载特定文件
  3. 该文件的内容是JSON和
  4. 您希望以后可以在其他JavaScript中使用JSON对象

如果是这种情况,那么您只需要执行以下操作即可:

$('#myPicker').change(function() {
    $('#container').empty();
    init($(this).val());
});

function init(jsonUrl){
  $.ajax({
    url:      jsonUrl
    dataType: 'json'
    success: function(response){
      // response should be automagically parsed into a JSON object
      // now you can just access the properties using dot notation:
        $('#container').html('<h1>' + response.property + '</h1>');
    }
  });
}




编辑:异常101表示the requester has asked the server to switch protocols and the server is acknowledging that it will do so [1]。 我认为,由于您使用的是file://foo/bar/... ,可能需要为$.ajax函数[2]切换isLocal标志,但是说实话,我不确定。

[1] http://en.wikipedia.org/wiki/Http_status_codes#1xx_Informational [2] http://api.jquery.com/jQuery.ajax/

下面是一个完整的工作示例,该示例从Twitter提取JSON对象,因此您应该能够将整个内容复制/粘贴到文件中,并在浏览器中运行它并使其正常工作。 如果您的服务器配置正确,并且.json文件位于document_root中并具有适当的权限,则您应该可以将它们换成Twitter URL并以相同的方式工作...

<!doctype html>
<html>
    <head>
        <title>My Super Rad Answer</title>
    </head>

    <body>
        <form id="my-form">
            <select id="cellTypePicker">
                <option value=''>No Value</option>
                <option value="AG10803-DS12374">AG10803-DS12374</option>
            </select>
        </form>
    </body>

    <!-- Grab the latest verson of jQuery -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript">

         // Wait until the page is fully loaded
         $(document).ready(function(){
            $('#cellTypePicker').change(function() {

                // Grab the value of the select field
                var name = $(this).val();


                if (!name) {
                  // Make sure it's not null...
                  // This is preferred over using === because if name is 
                  // anything but null, it will return fale
                  name = 'AG10803-DS12374';
                }

                // Right now I'm overwriting this to a resource that I KNOW 
                // will always work, unless Twitter is down.
                //
                // Make sure your files are in the right places with the 
                // right permissions...
                var jsonUrl = "http://api.twitter.com/help/test";

                $.ajax({
                    url: jsonUrl,
                    dataType: 'json',
                    success: function(response){
                        // JSON.stringify takes a JSON object and 
                        // turns it into a string
                        //
                        // This is super helpful for debugging
                        alert(JSON.stringify( response ));
                    },
                    error: function(xhr, textStatus, errorThrown){
                        alert("Error: " + textStatus + " | " + errorThrown + " | " + xhr);
                    }
                });
            });
         });
    </script>
</html>

您可以为此使用$.ajax() -或其中一种快捷方式,例如$.getJSON()

$.getJSON('somefile', function(data) {
    // here, data is javascript object represented by the json in somefile
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM