1
我是JSON和phonegap的新手,我嘗試開發一個應用程序來顯示來自web服務器的數據,但我無法在移動設備上的web視圖中顯示數據,我不知道我犯了什麼錯誤。這是我主要的html代碼:使用JSON xmlHttprequest從Web服務器讀取數據庫並顯示數據?
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #0055cc;
}
</style>
</head>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://databaseofalrais.site90.net/";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for (i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Street +
"</td><td>" +
arr[i].Phone +
"</td><td>" +
arr[i].Pincode +
"</td><td>" +
arr[i].Water +
"</td><td>" +
arr[i].Elec +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
我在URL中我提到的代碼,並在這裏舉辦的數據庫是PHP代碼來訪問數據庫,並使其作爲一個數組。
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html; charset=UTF-8");
$mysql_host = "mysql3.000webhost.com";
$mysql_database = "a4217438_data";
$mysql_user = "a4217438_admin";
$mysql_password = "admin123";
$conn = new mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
$result = $conn->query("SELECT * FROM Propertylist");
$outp = "[";
while ($rs = $result->fetch_array(MYSQLI_ASSOC)) {
if ($outp != "[") {
$outp .= ",";
}
$outp .= '{"Name":"' . $rs["CompanyName"] . '",';
$outp .= '"Street":"' . $rs["street"] . '",';
$outp .= '"Phone":"' . $rs["phone"] . '"}';
$outp .= '"Pincode":"' . $rs["pincode"] . '"}';
$outp .= '"Water":"' . $rs["water"] . '"}';
$outp .= '"Elec":"' . $rs["ele"] . '"}';
}
$outp .="]";
$conn->close();
echo($outp);
通過使用你的代碼我之前得到的輸出一樣。我的問題是,我不能在網頁上顯示數據。我的意思是在HTML數據不解析通過JSON – Abhilash 2014-09-24 10:32:04
你需要使用json_encode分析值,所以首先添加在json數組中的所有值比將數組對象放入json_encode()。而已。 – 2014-09-26 05:38:12
感謝Amit現在爲我工作。 – Abhilash 2014-09-29 06:20:46