簡體   English   中英

使用來自PHP的AJAX解析JSON數組

[英]Parse JSON array with AJAX from PHP

我在制作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;
});

我知道錯誤是在contacts.php顯示JSON結果的方式中發生的,或者我需要在js文件中進行更改。

謝謝您的幫助。

根據您上面的評論,我試圖重寫一個保持相同結構的解決方案,但是刪除了不必要的內容; 這就是代碼的樣子。 請注意,沒有對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');

為了能夠在JS中解析它,在PHP回顯行之前。

好的,非常感謝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;

?>

我會繼續尋找,但多虧您,我才前進了一步。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM