2016-12-18 115 views
0

我試圖通過ajax從我的數據庫中提取數據到drop_down_list1。並將其顯示到下一個drop_down_list2。我遵循幾乎完全一樣的東西,就像這個youtube tutorial,但它似乎不工作。用ajax自定義下拉列表

下面的代碼:

test.php的

<?php 
include("connection.php"); 
?> 
<html> 
<head> 
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<script type="text/JavaScript"> 
function State(){ 
    $('#stateddl').empty(); 
    $('#stateddl').append("<option>Loading...</option>"); 
    $('#districtddl').append("<option value='0'> - </option>"); 

    $.ajax({ 
     type:"POST", 
     url:"custom2.php", 
     contentType:"application/json; charset=utf-8", 
     dataType:"json", 
     success: function(data){ 
      $('#stateddl').empty(); 
      $('#stateddl').append("<option value='0'>-</option>"); 
      $.each(data,function(i,item){ 
       $('#stateddl').append('<option value="'+ data[i].roomName +'">'+ data[i].roomName+'</option>'); 
      }); 
     }, 
     complete: function(){ 
     } 
    }); 
} 
function District(sid){ 
    $('#districtddl').empty(); 
    $('#districtddl').append("<option>Loading...</option>"); 
    $.ajax({ 
     type:"POST", 
     url:"custom.php?sid="+sid, 
     contentType:"application/json; charset=utf-8", 
     dataType="json", 
     success: function(data){ 
      $('#districtddl').empty(); 
      $('#districtddl').append("<option value='0'> - </option>"); 
      $.each(data,function(i,item){ 
       $('#districtddl').append('<option value="'+ data[i].roomPrice +'">'+ data[i].roomPrice +'</option>'); 
      }); 
     }, 
     complete: function(){ 
     } 
    }); 
} 
$(document).ready(function(){ 
    State(); 
    $("#stateddl").change(function(){ 
     var roomName = $("#stateddl").val(); 
     District(roomName); 

    }); 
}); 

</script> 
</head> 

<body> 
<select name="stateddl" id="stateddl"></select> <select name="districtddl" id="districtddl"></select> 
</body> 
</html> 

custom2.php

<?php 
include("connection.php"); 

$sql=mysql_query("SELECT * FROM roomtype"); 
if(mysql_num_rows($sql)) 
{ 
    $data=array(); 
    while($row=mysql_fetch_array($sql)) 
    { 
     $data[] = array 
     (
     'roomName' => $row['roomName'] 
     ); 
} 
header('Content-type: application/json'); 
echo json_encode($data); 
} 
?> 

custom.php

<?php 
include("connection.php"); 

$sql=mysql_query("SELECT * FROM roomtype WHERE roomName='".$_GET["sid"]."'"); 
if(mysql_num_rows($sql)) 
{ 
$data=array(); 
while($row=mysql_fetch_array($sql)) 
{ 
    $data[] = array 
    (
     'sid' => $row['roomName'], 
     'roomPrice' => $row['roomPrice'] 
    ); 
} 
header('Content-type: application/json'); 
echo json_encode($data); 
} 
?> 
+1

你能指定「但它似乎不工作」?現在會發生什麼?錯誤? – Jeff

+0

它不會在下拉列表中顯示任何結果。既不是默認值,如<選項值='0'> -。 – Asyraf

回答

0

的問題是因爲以下功能塊,

function District(sid){ 
    ... 
    $.ajax({ 
     ... 
     dataType="json", 
     ... 
    }); 
} 

dataType設置AJAX請求的,錯=標誌。它應該是dataType:"json"

+0

我從不習慣Jquery和AJAX。所以我沒有關於它是如何工作的線索。謝謝。 – Asyraf