简体   繁体   中英

Should I use JSON and best practices when using JSON?

I am developing a site using Silverstripe, and a part of the site requires an interactive map similar to this - http://www.straytravel.asia/south-east-asia-bus-travel/

I am currently using AJAX to access all the information for each object (which includes, days, price, pass name etc) which changes onmouseover which works fine however load becomes an issue when browsing multiple items.

I would like to store the information for each pass locally which would allow me to retrieve the information faster. I haven't used JSON in a project and I am wondering if it is the best solution. I am currently able to retrieve all the pass information as JSON objects but I get stuck on how I should use it. Is it a good idea to store as a javascript variable and access the information via some jQuery calls or should I be approaching this problem differently? Does anyone have any good examples I can work off?

Thanks

JSON as a message format is the defacto standard for AJAX. It's more concise and readily parsed into JavaScript objects, and jQuery works with it very well (for example, using .ajax and setting the dataType to "json" will instruct jQuery to attempt to automatically parse resulting messages into objects from JSON).

Once you receive a JSON message and parse it into objects, "storage" is subjective. If you are merely keeping reference to the objects you've already downloaded to avoid downloading them again, you may simply have a map object to lookup and keep reference.

Assuming you are looking up info using some identifier, here's a rough example:

var infocache = {}; // keeps copy of previously retrieved info messages

function displayInfo(infoId) { // called when you want to display info, using some identifier
   var callback = function() {
       var info = infocache[infoId];

       // do something with your info object... display in HTML template or whatever.
   };

   if (infocache[infoId]) { 
     callback();
     return;
   }

   $.ajax({
      url:'/myapi/info/get', 
      data: {id: infoId }, 
      dataType:'json', 
      type:'POST', 
      success: function(result) {
             infocache[infoId] = result;
             callback();
           }
     }); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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