[英]How to use json and ajax to create a javascript array from a PHP array?
嘗試使用JSON和AJAX從URL的PHP數組創建JavaScript數組到圖像。 然后,我想在cordova應用程序上顯示圖像。 我相信我的問題是我正在接收或發送帶有自動html標簽的Json消息。 我的xmlhttp.response等於網址數組,但是它具有HTML標記,這些標記在PHP文件中不存在。 我認為由於這些標簽,我的JSON.parse無法正常工作?
這是我的PHP存儲在服務器上。 我返回json消息中的網址。
<?php
include("mysqlconnect.php");
$select_query = "SELECT `ImagesPath` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
$data[] = $row['ImagesPath'];
}
echo json_encode($data);
?>
這是我的cordova應用程序中的腳本。 我想將JSON消息轉換為javaScript數組,並在div內容中顯示數組中的第一個圖像。 但是我認為我正在呼叫包含html標簽的消息,因此我無法解析該消息,這可能是錯誤的。 我現在收到三個錯誤警報,因為就緒狀態不正確。
<html>
<script>
var arr = [];
function importJson(str) {
if (str=="") {
document.getElementById("content").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
alert(xmlhttp.response);
arr = JSON.parse(xmlhttp.response);
//var arr = (array)json.parse(xmlhttp.response);
for (var i = 0; i < arr.length; i++) {
buildImage(arr[i]);
alert(arr[0]);
}
} else {
alert("Error");
}
}
xmlhttp.open("GET","http://server/~name/folder/content.php);
xmlhttp.responseType = "json";
xmlhttp.send();
buildImage=function(src) {
var img = document.createElement('img');
img.src = src;
document.getElementById("content").appendChild(img);
}
}
window.onload = importJson();
</script>
<body>
<div id="content"></div>
目前,您的PHP腳本正在輸出網頁,但是javascript正在尋找JSON。 要輸出JSON,您需要在php腳本中設置標頭:
header('Content-Type: application/json');
echo json_encode($data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.