简体   繁体   English

使用来自PHP的AJAX解析JSON数组

[英]Parse JSON array with AJAX from PHP

I am having trouble making an PHP API to get data from MYSQL and parse JSON. 我在制作PHP API以从MYSQL获取数据并解析JSON时遇到了麻烦。 I have a demo app (hiApp) and comes with some JSON files inside a folder. 我有一个演示应用程序(hiApp),并且在文件夹中随附了一些JSON文件。

The demo JSON file is like this: 演示JSON文件如下所示:

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

This what my contacts.php is returning: 这是我的contacts.php返回的内容:

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

My contacts.php api looks like this: … 我的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);

?>

The js file to parse JSON, looks like this: 解析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;
});

I know the error is in the way contacts.php is displaying the JSON results or I need to change something in the js file. 我知道错误是在contacts.php显示JSON结果的方式中发生的,或者我需要在js文件中进行更改。

Thanks for the help. 谢谢您的帮助。

Based on your comments above I've tried to rewrite a solution keeping the same structure, but removing the unnecessary things; 根据您上面的评论,我试图重写一个保持相同结构的解决方案,但是删除了不必要的内容; this is what the code may look like. 这就是代码的样子。 Note that there are no references to err_code and err_msg peoperties, and the callback is called directly on data variable. 请注意,没有对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;
});

Then you may call it this way, using directly response var, which now contains the parsed data array: 然后,您可以使用直接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
                }); 
            } 
        }); 
    } 
}

Also, you would have to add 另外,您必须添加

header('Content-Type: application/json');

before your PHP echo line in order to be able to parse it in JS. 为了能够在JS中解析它,在PHP回显行之前。

Ok, many thanks Andrea, looks like there is something else that I'm missing because the results from the contacts.php and the initial contacts.php file is the same in my browser: 好的,非常感谢Andrea,我似乎还缺少其他东西,因为从我的浏览器中contacts.php和初始contacts.php文件的结果是相同的:

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

It works just fine if I use the initial contacts.php that only has pure json data like above, but if I switch to my api it stops working. 如果我使用仅具有如上所述纯json数据的初始contacts.php,它就可以正常工作,但是如果我切换到api,它将停止工作。

Also it stops working if I use this in the initial contacts.php: 如果我在最初的contacts.php中使用它,它也会停止工作:

<?php

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

?>

I'll keep looking, but thanks to you I'm one step ahead. 我会继续寻找,但多亏您,我才前进了一步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM