解析JSON输出问题

时间:2013-02-24 09:35:05

标签: json jquery-mobile

我正在呼叫服务以获取基于国家/地区的语言。当它返回多种语言时,我的下面代码工作正常..但是当它只返回一条记录时输出没有正确显示(来自“未定义”..请建议。

这是我的代码:

$.ajax({
            type: 'POST',
            url: "http://mymethod",
            complete: function () { $.mobile.hidePageLoadingMsg(); },
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify({
                "country": countryCode
            }),
            success: function (output, textStatus, jqXHR) {
                $.each(output.geographyInfo, function (i, theItem) {
                    try {
                        languages.push("<option value='" + theItem.languageCode + "'>" + theItem.languageName + "</option>");
                    }
                    catch (error) {
                        alert(error);
                    }
                });
                $(languages.join('')).appendTo("#dpdLanguages").trigger("create");
            }
        });

这是json输出。

这里只有一种语言的输出:

{“geographyInfo”:{“active”:“true”,“countryCode”:“US”,“countryName”:“UNITED STATES”,“instanceID”:“1”,“languageCode”:“EN”, “languageName”:“English”,“regionName”:“North America”},“reasonDetails”:null,“size”:“1”,“status”:“true”}

并且在多个案例中

{ “geographyInfo”:[{ “活性”: “真”, “COUNTRYCODE”: “CA”, “国家名称”: “加拿大”, “实例ID”: “1”, “语言代码”: “EN”, “languageName”:“English”,“regionName”:“North America”},{“active”:“true”,“countryCode”:“CA”,“countryName”:“CANADA”,“instanceID”:“1” ,“languageCode”:“FR”,“languageName”:“french”,“regionName”:“North America”},{“active”:“true”,“countryCode”:“CA”,“countryName”:“CANADA ”, “实例ID”: “2”, “语言代码”: “EN”, “languageName”: “英语”, “regionName”: “美洲”}, { “主动”: “真”, “COUNTRYCODE”: “CA”, “国家名称”: “加拿大”, “实例ID”: “2”, “语言代码”: “FR”, “languageName”: “法国”,” regionName “:” 美洲 “}],” reasonDetails “:空,” 尺寸 “:” 4" , “状态”: “真”}

是的udidu,我认为就是这样......但是如何解决这个问题呢?

1 个答案:

答案 0 :(得分:1)

这里最简单的解决方案是,如果你只有一个geographyInfo元素将它包装在[]中,就像这样:

{"geographyInfo":[{"active":"true","countryCode":"US","countryName":"UNITED STATES","instanceID":"1","languageCode":"EN","languageName":"English","regionName":"North America"}],"reasonDetails":null,"size":"1","status":"true"}

因此,它将作为一个元素数组,您不需要更改代码。目前,当只有一个geographyInfo元素时,每个循环都会将内部geographyInfo项显示为单独的数组元素,并且它将循环7次。

这是一个有效的例子:

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>jQM Complex Demo</title>
    <meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>    
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>    
    <script>
        $(document).on('pagebeforeshow', '#index', function(){     
            $('#populate-button').on('click',function(e,data){     
                $('#dpdLanguages').empty()
                $.ajax({
                    type: 'POST',
                    url: "json.php",
                    complete: function () { $.mobile.hidePageLoadingMsg(); },
                    dataType: "json",
                    contentType: 'application/json',
                    data: "",
                    success: function (output, textStatus, jqXHR) {
                        $.each(output.geographyInfo, function (i, theItem) {
                            try {
                                $('<option>').attr('value',theItem.languageCode).html(theItem.languageName).appendTo("#dpdLanguages");
                            }
                            catch (error) {
                                alert(error);
                            }
                        });
                        $('#dpdLanguages').selectmenu();  
                    }
                });
            });        
        });
    </script>
</head>
<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
        </div>

        <div data-role="content">
            <a href="#" data-role="button" id="populate-button">Load JSON data</a>
            <select id="dpdLanguages"></select>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>    
</body>
</html>   

jsop.php:

<?php
    echo '{"geographyInfo":[{"active":"true","countryCode":"US","countryName":"UNITED STATES","instanceID":"1","languageCode":"EN","languageName":"English","regionName":"North America"}],"reasonDetails":null,"size":"1","status":"true"}';    
?>

编辑:

如果您无法更改JSON代码,这也可以使用:

$(document).on('pagebeforeshow', '#index', function(){     
    $('#populate-button').on('click',function(e,data){     
        $('#dpdLanguages').empty()
        $.ajax({
            type: 'POST',
            url: "json.php",
            complete: function () { $.mobile.hidePageLoadingMsg(); },
            dataType: "json",
            contentType: 'application/json',
            data: "",
            success: function (output, textStatus, jqXHR) {
                if(typeof output.geographyInfo.length !== 'undefined') {                                      
                    $.each(output.geographyInfo, function (i, theItem) {
                        try {
                            $('<option>').attr('value',theItem.languageCode).html(theItem.languageName).appendTo("#dpdLanguages");
                        }
                        catch (error) {
                            alert(error);
                        }
                    });
                } else {
                    $('<option>').attr('value',output.geographyInfo['languageCode']).html(output.geographyInfo['languageName']).appendTo("#dpdLanguages");
                }
                $('#dpdLanguages').selectmenu();                            
            }
        });
    });        
});