这是我的 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: jQuery.parseJSON@http://localhost/search/js/vendor/jquery.js:7964:9 ajaxConvert@http://localhost/search/js/vendor/jquery.js:8246:19 done@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 :
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 调用未收到数据。我发现,success
在调用 php 文件之前先执行。我设置了async:false,没有效果。
然后我在 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… }
最佳答案
你需要
echo json_encode($data);
以便将数据发送到 XHR 请求。仅仅返回
是行不通的
关于javascript - PHP 不向 ajax 调用返回数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43485620/