我正在创建一个API。这是我的PHP函数。
function get_schools($cn){
$schools = "SELECT * FROM schools";
$school_result = mysqli_query($cn, $schools);
$response_array['form_data']['schools'] = '';
$school_array = array();
while ($school_row = mysqli_fetch_assoc($school_result)) {
$school_array[$school_row['school_id']] = $school_row['school_name'];
}
$response_array['status'] = 'success';
$response_array['form_data']['schools'] = $school_array;
echo json_encode($response_array);
}
这是我的js。
getSchools();
function getSchools(){
var requestDATA = {
'request': 'get_schools'
}
myApp.showIndicator();
serverRequest(requestDATA, getSchoolsSuccess, responseError, true, true);
}
function getSchoolsSuccess(){
if(hideIndicator){
myApp.hideIndicator();
}
console.log(data);
if(data.status == 'success'){
}else if (data.status == 'error'){
requestFailure(data.status, data.message, showAlert);
} else if (data.status == '') {
requestFailure(data.status, data.message, showAlert);
}
}
/* AJAX Request Function */
function serverRequest(requestDATA, successCallback, errorCallback, hideIndicator, showAlert){
var METHOD = "POST";
var serverURL = 'http://localhost/istudy/server.php'; //Path to Server.php
var DATA_TYPE = 'json';
var TIMEOUT = 20000;
console.log(requestDATA);
$$.ajax({
url: serverURL,
data: requestDATA,
dataType: DATA_TYPE,
type: METHOD,
timeout: TIMEOUT,
success: function(data){
successCallback(data, hideIndicator, showAlert);
},
error: function(a, b, c){
errorCallback(a, b, c, hideIndicator, showAlert);
}
});
}
/* Function to handle request error */
function responseError(xhr, textStatus, errorThrown, hideIndicator, showAlert){
console.log(xhr);
console.log(textStatus);
console.log(errorThrown);
var error_message = "";
switch(textStatus){
case 'error':
error_message = "Please check your internet connection and try again.";
break;
case 'parsererror':
error_message = "Internal error occureed. Report application administrator about this error.";
break;
case 'timeout':
error_message = "Slow internet may be. Pull down to refresh page.";
break;
case 'abort':
error_message = "The request was aborted.";
break;
default:
error_message = "Cannot reach server at this time. You can report this error.";
break;
}
if(hideIndicator){
myApp.hideIndicator();
}
if(showAlert){
myApp.alert(error_message, "Oh Snap! :(", null);
}
}
/* Request With Server Fail or Error or Others */
function requestFailure(status, message, showAlert){
if(showAlert){
if(status == 'error'){
myApp.alert(message, 'No Data Available!', null);
}else if(status == ''){
myApp.alert(message, 'Request Failure!', null);
}else{
if(showAlert){
myApp.alert("Application was not ready to serve this request at this time.", 'Unknown Response', null);
}
}
}
}
一切正常。查询也会在responseText中获取结果,但我得到了parseerror。知道可能是什么问题吗?
请参阅下面附图。
可能是什么问题?
答案 0 :(得分:0)
由于您要将DATA_TYPE
定义为json
,这意味着执行请求后发送的数据已转换为array
。这就是你得到parse error