最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Loading JSON into JavaScript variable locally without server-side script? - Stack Overflow

programmeradmin1浏览0评论

I have 41 JSON objects, each with the same scheme.

These objects are fairly large, and so I would like to load the object conditionally into a JavaScript script, when selecting an <option> from a <select> menu with an id of myPicker.

So far, I have set up jQuery to handle changes on the <select>:

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

The function init() draws stuff in div called container.

When I change myPicker, I want init() to behave like init(value), which in turn tells init to load one of 41 JSON objects from a file (based on value).

Is loading a chunk of JSON from a file (located on the server-side) doable in this case, or do I need to use a server-side script handling Ajax form submissions and responses, etc.?

EDIT

I wrote the following code:

<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();">
...

The line alert("Success!"); never gets called.

Instead, I get the following error:

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

I am checking the value jsonUrl and it appears to be a proper URL. The file that it points to is present and I have permissions to access it (it is sitting in my home folder). Is there something I am still missing?

I have 41 JSON objects, each with the same scheme.

These objects are fairly large, and so I would like to load the object conditionally into a JavaScript script, when selecting an <option> from a <select> menu with an id of myPicker.

So far, I have set up jQuery to handle changes on the <select>:

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

The function init() draws stuff in div called container.

When I change myPicker, I want init() to behave like init(value), which in turn tells init to load one of 41 JSON objects from a file (based on value).

Is loading a chunk of JSON from a file (located on the server-side) doable in this case, or do I need to use a server-side script handling Ajax form submissions and responses, etc.?

EDIT

I wrote the following code:

<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();">
...

The line alert("Success!"); never gets called.

Instead, I get the following error:

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

I am checking the value jsonUrl and it appears to be a proper URL. The file that it points to is present and I have permissions to access it (it is sitting in my home folder). Is there something I am still missing?

Share Improve this question edited Feb 18, 2012 at 2:28 Alex Reynolds asked Feb 18, 2012 at 0:55 Alex ReynoldsAlex Reynolds 97.1k59 gold badges250 silver badges351 bronze badges 3
  • There is .val() to get the value of an element - do not use .attr('value')! – ThiefMaster Commented Feb 18, 2012 at 1:09
  • What browser are you using? Based upon stackoverflow./questions/6965942/… , and its relevant links, it seems Google Chrome will give that error for local files requested using ajax. Does another browser, like Firefox work? – MJD Commented Feb 18, 2012 at 6:51
  • Neither Safari nor Chrome seem to work with file:// URLs. Is this a known bug? – Alex Reynolds Commented Feb 18, 2012 at 8:55
Add a ment  | 

2 Answers 2

Reset to default 4

Let me make sure I understand your question. I think you want to:

  1. have a handful of files out there that contain JSON objects
  2. depending on which option is selected a particular file is loaded
  3. the contents of the file is JSON and
  4. you want to be able to use the JSON object later on in other javascript

If this is the case then you would just need to do something like:

$('#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>');
    }
  });
}




EDIT: Exception 101 means the requester has asked the server to switch protocols and the server is acknowledging that it will do so[1]. I think since you're using file://foo/bar/... you might need to toggle the isLocal flag for the $.ajax function [2], but honestly, I'm not sure.

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

Below is a plete working example that pulls a JSON object from Twitter, so you should be able to copy/paste the entire thing into a file and run it in a browser and have it work. If your server is configured correctly and your .json files are in the document_root and have the appropriate permissions, you should be able to swap them out for the Twitter URL and have it work the same way...

<!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./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./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>

You can use $.ajax() for this - or one of the shortcuts, e.g. $.getJSON():

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

评论列表(0)

  1. 暂无评论