我在最近10個小時遇到了一個奇怪的問題,它真的很煩人。問題出在jQuery打印來自php的json數據。 php腳本運行良好,但是當ajax調用返回完成時:事件我沒有得到任何有效的輸出。jquery ajax不解析php的json數據
這裏是jQuery代碼::
list_choice = "A";
content_choice = "Artists"; //globals to store default value
$(document).ready(function() {
$('.list-nav > a').click(function() {
var ltext = $(this).text();
list_choice = ltext;
console.log(ltext+" <------> ");
$.ajax({
url: 'retrieveFileFront.php',
data: {type: content_choice, navtext: list_choice},
type: 'POST',
dataType: 'json',
complete: function(data) {
console.log(data['message']['Album_Name']);
}
});
return false;
});
});
我不得不使用complete:event作爲成功:根本沒有工作。至少我從完整的事件中得到某種輸出,儘管它給出undefined
或[object][Object]
這是完全荒謬的。
這裏是retrieveFileFront.php
:
<?php
require './retrieveFiles.php';
$type = $_POST['type'];
$nav_text = $_POST['navtext'];
$ret_files = new retrieveFiles($type, $nav_text);
$data = $ret_files->retFiles();
if ($data['success'] == FALSE) {
$data = array('success' => FALSE, 'message' => 'Sorry an Error has occured');
echo json_encode($data);
} else {
echo json_encode($data);
}
>
這裏是/retrieveFiles.php
<?php
class retrieveFiles {
public $content_type;
public $list_nav;
public $connection;
public $result;
public $result_obj;
public $tags_array;
public $query;
public $row;
public function __construct($type, $nav_text) {
$this->content_type = $type;
$this->list_nav = $nav_text;
}
public function retFiles() {
@$this->connection = new mysqli('localhost', 'usr', 'pass', 'data');
if(!$this->connection) {
die("Sorry Database connection could not be made please try again later. Sorry for the inconvenience..");
}
if ($this->content_type == "Artists") {
$this->query = "SELECT album_name, album_art FROM album_dummy NATURAL JOIN album_images_dummy WHERE artist_name LIKE '$this->list_nav%'";
try {
$this->result = $this->connection->query($this->query);
$this->row = $this->result->fetch_row();
if (isset($this->row[0]) && isset($this->row[1])) {
$this->tags_array = array("success" => true, "message" => array("Album_Name" => $this->row[0], "Album_Art" => $this->row[1]));
return $this->tags_array;
}
} catch (Exception $e) {
echo 'Sorry an Error has occurred'.$e;
return false;
}
}
}
}
>
我得到在控制檯200響應?螢火蟲,這表明它的運行沒問題。
<!DOCTYPE HTML>
{"success":true,"message":{"Album_Name":"Streetcleaner","Album_Art":"\/var\/www\/html\/MusicLibrary\/Musics\/1989 - Streetcleaner\/folder.jpg"}}
現在,這是使我更糊塗了,因爲我可以看到JSON格式正確。請提供任何關於如何解決此問題的建議。
在此先感謝..
您是否在您的JSON響應中添加了一個'<!DOCTYPE HTML>'前綴? – techfoobar
1。您的JSON響應中不應該包含該HTML文檔類型; 2.你不應該打印本地路徑到文件,而是URL。 – moonwave99
響應以字符串形式發送,而不是Javascript對象。請參閱下面的答案。 –