這是我的AJAX調用:腓不將數據返回到AJAX調用
var urlstring = '/search/';
$.ajax({
url: urlstring+'model.php',
type: 'GET',
dataType: 'text',
'data': 'test=1',
error: function(xhr, status, error) {
console.debug(error);
},
success: function() {
console.log('success');
},
complete: function(data) {
console.log('complete');
console.debug(data);
}
});
當我改變dataType: 'json'
,我得到這個錯誤:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data Stack trace: [email protected]http://localhost/search/js/vendor/jquery.js:7964:9 [email protected]http://localhost/search/js/vendor/jquery.js:8246:19 [email protected]http://localhost/search/js/vendor/jquery.js:8707:15 .send/callback/<@http://localhost/search/js/vendor/jquery.js:9123:9
我返回的數據從PHP這樣的JSON類型:
json_encode($data);
我還嘗試在返回數據之前設置標題:
header('Content-Type: application/json');
現在我試圖改變dataType: 'text'
:
在PHP文件,
<?php
include 'config.php';
class SearchModel extends Database
{
public $searchModel = null;
public function __construct()
{
$database = new Database();
}
public function fetchLocations()
{
$query = array();
$query[] = "SELECT * FROM `tbl_location`";
$query = implode(' ', $query);
$statement = self::$connection->prepare($query);
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
return $data;
}
}
$searchModel = new SearchModel();
if (isset($_GET['test'])) {
$data = $searchModel->fetchLocations();
// header('Content-Type: application/json');
return $data;
}
?>
不是我的Ajax調用接收到的數據。我發現,在調用php文件之前,success
正在執行。我設置異步:假,無濟於事。
然後我在下面加success
和complete
這個時候我看到AJAX是得到的東西比我從服務器期待其他數據:
Object { readyState: 4, getResponseHeader: .ajax/jqXHR.getResponseHeader(), getAllResponseHeaders: .ajax/jqXHR.getAllResponseHeaders(), setRequestHeader: .ajax/jqXHR.setRequestHeader(), overrideMimeType: .ajax/jqXHR.overrideMimeType(), statusCode: .ajax/jqXHR.statusCode(), abort: .ajax/jqXHR.abort(), state: .Deferred/promise.state(), always: .Deferred/promise.always(), then: .Deferred/promise.then(), 11 more… }
您需要回顯數據,而不是返回。在所有 – nogad
嘗試echo後,js正在讀取外部文件,但仍然沒有得到數據表單服務器,但是這樣:Object {readyState:4,getResponseHeader:.ajax/jqXHR.getResponseHeader(),getAllResponseHeaders:.ajax/jqXHR .getAllResponseHeaders(),setRequestHeader:.ajax/jqXHR.setRequestHeader(),overrideMimeType:.ajax/jqXHR.overrideMimeType(),statusCode:.ajax/jqXHR.statusCode(),abort:.ajax/jqXHR.abort() :.Deferred/promise.state(),總是:.Deferred/promise.always(),然後:.Deferred/promise.then(),更多...} – 112233
@nogad,我在網絡選項卡中檢查,它顯示正確的json字符串。但它不會傳遞給ajax調用。我懷疑它有什麼問題。給出的網址是正確的。 – 112233