使用PHP的AJAX解析JSON数组

时间:2014-10-30 10:00:01

标签: javascript php ajax json api

我无法使用PHP API从MYSQL获取数据并解析JSON。我有一个演示应用程序(hiApp),并在文件夹中附带一些JSON文件。

演示JSON文件是这样的:

{ "err_code": 0, "err_msg": "success", "data": [{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]}

这是我的contacts.php返回的内容:

[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]

我的contacts.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文件中的内容。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

根据您的上述评论,我尝试重写一个保持相同结构的解决方案,但删除了不必要的东西;这就是代码的样子。请注意,没有对err_codeerr_msg peoperties的引用,并且回调是直接在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回显行之前,以便能够在JS中解析它。

答案 1 :(得分:0)

好的,非常感谢Andrea,看起来我还缺少其他东西,因为来自contacts.php和初始contacts.php文件的结果在我的浏览器中是相同的:

[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]

如果我使用仅具有上述纯json数据的初始contacts.php,它可以正常工作,但是如果我切换到我的api它就会停止工作。

如果我在初始contacts.php中使用它,它也会停止工作:

<?php

$myString = '[{"nickname":"Joao","location":"I.13"},{"nickname":"Victor","location":"2811"}]';
echo $myString;

?>

我一直在寻找,但多亏了你,我领先一步。