我在制作 PHP API 从 MYSQL 获取数据并解析 JSON 时遇到问题。我有一个演示应用程序 (hiApp),并在文件夹内附带了一些 JSON 文件。
演示 JSON 文件如下:
{ "err_code": 0, "err_msg": "success", "data": [{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]}
这是我的 contact.php 返回的内容:
[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]
我的 contact.php api 如下所示: ...
…
$result = mysql_query("select * from sellers", $db);
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['nickname'] = $row['first_name'];
$row_array['location'] = $row['territory'];
array_push($json_response,$row_array);
}
echo json_encode($json_response);
?>
解析 JSON 的 js 文件,如下所示:
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
search: function(code, array){
for (var i=0;i< array.length; i++){
if (array[i].code === code) {
return array[i];
}
}
return false;
},
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data ? JSON.parse(data) : '';
var codes = [
{code:10000, message:'Your session is invalid, please login again',path:'/'},
{code:10001, message:'Unknown error,please login again',path:'tpl/login.html'},
{code:20001, message:'User name or password does not match',path:'/'}
];
var codeLevel = xhr.search(data.err_code,codes);
if(!codeLevel){
(typeof(callback) === 'function') ? callback(data) : '';
}else{
hiApp.alert(codeLevel.message,function(){
if(codeLevel.path !== '/')
mainView.loadPage(codeLevel.path);
hiApp.hideIndicator();
hiApp.hidePreloader();
});
}
}
});
}
};
return xhr;
});
我知道错误出在 contact.php 显示 JSON 结果的方式上,或者我需要更改 js 文件中的某些内容。
感谢您的帮助。
最佳答案
根据您上面的评论,我尝试重写一个解决方案,保持相同的结构,但删除不必要的东西;这就是代码的样子。请注意,没有对 err_code
和 err_msg
对象的引用,并且直接在 data
变量上调用回调。
define(['utils/appFunc',
'i18n!nls/lang',
'components/networkStatus'],function(appFunc,i18n,networkStatus) {
//var apiServerHost = window.location.href;
var xhr = {
getRequestURL: function(options){
//var host = apiServerHost || window.location.host;
//var port = options.port || window.location.port;
var query = options.query || {};
var func = options.func || '';
var apiServer = 'api/' + func + '.php' +
(appFunc.isEmpty(query) ? '' : '?');
var name;
for (name in query) {
apiServer += name + '=' + query[name] + '&';
}
return apiServer.replace(/&$/gi, '');
},
simpleCall: function(options,callback){
options = options || {};
options.data = options.data ? options.data : '';
//If you access your server api ,please user `post` method.
//options.method = options.method || 'GET';
options.method = options.method || 'POST';
if(appFunc.isPhonegap()){
//Check network connection
var network = networkStatus.checkConnection();
if(network === 'NoNetwork'){
hiApp.alert(i18n.error.no_network,function(){
hiApp.hideIndicator();
hiApp.hidePreloader();
});
return false;
}
}
$$.ajax({
url: xhr.getRequestURL(options) ,
method: options.method,
data: options.data,
success:function(data){
data = data.length > 0 ? JSON.parse(data) : [];
if (typeof(callback) === 'function' && data !== undefined)
callback(data);
}
});
}
};
return xhr;
});
然后你可以这样调用它,直接使用 response
var,它现在包含解析的数据数组:
loadContacts: function() {
if(VM.module('contactView').beforeLoadContacts()) {
xhr.simpleCall({
query: { callback: '?' },
func: 'contacts'
}, function (response) {
if (response !== undefined) {
VM.module('contactView').render({
contacts: response
});
}
});
}
}
此外,您还必须添加
header('Content-Type: application/json');
在 PHP echo 行之前,以便能够在 JS 中解析它。
关于javascript - 从 PHP 使用 AJAX 解析 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26649986/