How to use a JSON file in javascript

前端 未结 1 1453
后悔当初
后悔当初 2020-11-30 02:36

First off, I am a newcomer to the Javascript realm. I have a JSON file, such as the following:

{\"markers\": [
  {
   \"abbreviation\": \"SPA\",
   \"latitud         


        
相关标签:
1条回答
  • 2020-11-30 03:17

    First you need a handle on a file. You need to get it somehow either through ajax or through server-side behaviour.

    You need to tell use where the file is. How you plan to get it and what serverside code your using.

    Once you have you can use JSON.parse(string) on it. You can include the json2.js file if you need to support older browsers.

    If you use jQuery you can also try jQuery.parseJSON for parsing instead.

    An option for remotely getting json would be using jQuery.getJSON

    To load it you can either use JSONP or some kind of library with ajax functionality like jQuery.ajax or Ajax.Request. It can be done in raw javascript but that's just ugly and re-inventing the wheel.

    $.getJSON("document.json", function(data) {
        console.log(data);
        // data is a JavaScript object now. Handle it as such
    
    });
    
    0 讨论(0)
提交回复
热议问题