javascript - Using AJAX to retrieve data from JSON File -


so trying read data json file , display on webpage using html. work simple keys particular database wouldn't work me.

json:

var carinfo = [ {     carid: 1,     carprice : 15.00, }, {     carid: 2,     carprice : 25.00, } ]; 

js:

$(document).ready(function() {      $.getjson("vehicle_data.json", function(data) {          $.each(data.carinfo, function() {              $("ul").append("<li>car id: "+this[carinfo[0].carid]);          });              });      }); 

html:

<html> <body> <ul></ul> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="json_data_retrieve.js"></script> </body> </html> 

it not valid json file. js script.

var carinfo = [     {         carid: 1,         carprice : 15.00,     },     {         carid: 2,         carprice : 25.00,     } ]; 

try this:

{     "carinfo":      [         {             "carid": 1,             "carprice": 15         },         {             "carid": 2,             "carprice": 25         }     ] } 

update:
may load script script source in html. must .js file.

<script src="vehicle_data.js"></script> 

if need load dynamically, use jquery $.getscript method. doesn't matter has .json extensions because evaluated script.

$(document).ready(function()  {     $.getscript("vehicle_data.json", function()      {         // pay attention. in case, work carinfo          // variable because has been executed script,          // not loaded json file.         $.each(carinfo, function()             {             $("ul").append("<li>car id: " + this[carinfo[0].carid]);         });              });      }); 

however, very strange gives .json file js declaration , tells you should execute shouldn't rename or load script.


Comments