0
我是新的Ajax和JSON表示法,所以我試圖從數據庫的不同表中獲取數據,數據如國家名稱,州名,出事名稱,工作位置等等,我見過的例子是如何通過JSON獲取數據,但只是從一個表中,你能給我一點幫助,我怎樣才能用多個表來完成它,並將它保存在一個數組中。從各種查詢檢索多個數據與AJAX php mysql
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
HTML文件:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
mysql_fetch_row在這種情況下無用。改爲使用mysql_fetch_assoc。您可以獲得關聯的json屬性。 data.name,data.country,data.id ... – Panoptik 2014-11-04 16:59:41