หน้าเว็บ

วันอาทิตย์ที่ 12 กุมภาพันธ์ พ.ศ. 2555

AJAX (jquery) request PHP JSON

PHP
query.php
 <?php
    $host = "localhost";
    $user = "root";
    $password = "password";
    @mysql_connect($host,$user,$password) or die("unable connect to database!");    
    mysql_select_db("learning_mysql_db");
    $result_set = mysql_query("select * from tb_student");
    $JSON = array();
    if($result_set == true){
         while($data = mysql_fetch_array($result_set)){
             $JSON[] = array(
                  "std_code" => $data["std_code"],
                 "std_name" => $data["std_name"],
                "std_grade" => $data["std_grade"]
             );
        }
    }
    mysql_close();
    echo json_encode($JSON);
?>
------------------------------------------------------------------------
JQuery
$(document).ready(function(){
    query();
});

function query(){
    $.ajax({
        type : 'get',        
        dataType : 'html',
        data : null,
        url : '../php/query.php',    
        success : function(r){
            var obj_std = eval("("+r+")"); 
            var html = resultPattern(obj_std);
            $("#result").html(html); 
        }    
    });                
}

------------------------------------------------------------------------
function resultPattern(obj_std){
.
..
...
    for(i=0;i<obj_std.length;i++){ 
       html+="<tr>";
         html+="<td class='no'>"+(i+1)+"</td>";
         html+="<td class='std_code'>"+obj_std[i].std_code+"</td>";
         html+="<td class='std_name'>"+obj_std[i].std_name+"</td>";
         html+="<td class='std_grade'>"+obj_std[i].std_grade+"</td>";
         html+="<td><img name='edit' src='../image/edit.png'/></td>";
         html+="<td><img name='delete' src='../image/delete.png'/></td>";
       html+="</tr>";
    }       
.
..
...
    return html;
}
Respose from query.php





อ่านเพิ่มเติมได้ที่ 
เจสัน(JSON) คืออะไร :  http://na5cent.blogspot.com/2012/03/json.html  
php JSON encode : http://php.net/manual/en/function.json-encode.php             
                 

ไม่มีความคิดเห็น:

แสดงความคิดเห็น