我有一个 html 页面,它将发送 json 请求以从服务器获取数据 [尽管 php-mysql]。我看到没有收到回复。我尝试通过 fiddler 进行调试,可以看到“响应不包含有效的 json 文本。
我的代码如下
html
<!DOCTYPE html>
<html>
<script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript">
</script>
<script type="text/javascript">
function populateFruitVariety() {
$.getJSON('serverside.php',
{fruitName:$('#fruitName').val()},
function(data) {
var select = $('#fruitVariety');
if(select.prop) {
var options = select.attr('options');
} else {
var options = select.attr('options');
}
$('option', select).remove();
$.each(data, function(val, text) {
options[options.length] = new Option(text, val);
});
});
}
$(document).ready(function() {
populateFruitVariety();
$('#fruitName').change(function() {
populateFruitVariety();
});
});
</script>
<form>
Fruit:
<select name="name" id="fruitName">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
<option>Pear</option>
</select>
Variety:
<select name="variety" id="fruitVariety">
</select>
</form>
</html>
服务器端.php
<?php
header('Content-type: application/json');
$host="localhost";
$username="root";
$password="";
$database="db_common";
$table_fruit_info = "fruit_info";
$tc_fruit_id = "fruit_id";
$tc_fruit_index = 'fruit_index';
$con = mysql_connect("$host", "$username", "$password")
or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
if(isset($_GET['fruitName'])) {
$fruit_id = $_GET['fruitName'];
$result = mysql_query("SELECT * FROM $table_fruit_info
WHERE $tc_fruit_id='$fruit_id'");
while($rows = mysql_fetch_array($result))
{
$ret_fruitIndex = $rows[$tc_fruit_index];
}
}
echo json_encode($ret_fruitIndex);
?>
谢谢你的帮助!