Friday, 29 July 2011

Get JSON from a PHP file and load it onto the page using jQuery

json.php
<?php

//create an array and convert it into json

$boats =array(
    "sundancer",
    "bayliner",
    "hatchback");


header('Content-type:application/json');
echo json_encode($boats);
?>

The header when viewed from Firebug looks like this,

index.php


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="script.js"></script>
<style type="text/css">

</style>
</head>
<body>
    <div>
        <select name="boat" id="boatList">
            <option value="">Select an option</option>
        </select>
    </div>
</body>
</html>


javscript


$(function(){
   $.getJSON('json.php',function(json){
       var select=$('#boatList');
       
       $.each(json, function(index,value){
          var option=$('<option>');
          
          option.attr('value',value)
                .html(value)
                .appendTo(select);
       });
   }) ;
});

No comments:

Post a Comment