php脚本上没有显示JSON数据

时间:2015-05-19 05:50:01

标签: javascript php json

我有json数据,如下所示:

{
"firmware": [
    {
        "Request": "/Firmware/samsung",
        "Count": "2954"
    },
    {
        "Request": "/Firmware/apple",
        "Count": "2954"
    }
],
"exe": [
    {
        "Request": "/applications/appstore.exe",
        "Count": "4482"
    }
]    
}

我试图通过PHP脚本阅读它并显示它。但没有看到任何数据。脚本如下:

<script type="text/javascript" src="http://localhost/json/softwarelogs.js"></script>
<fieldset class="light" style="width: 60%; margin-right: 20px; margin-bottom: 20px; float: left;" >
<legend>Top Firmware Downloads</legend>
<div class="statlist" id="topFirmware"> </div>
</fieldset>

<fieldset class="light" style="width: 60%; margin-right: 20px; margin-bottom: 20px; float: left;">
<legend>Top EXE Downloads</legend>
<div class="statlist" id="exe"> </div>
</fieldset>

<script>
   var htmlString = "<ol>";
   $.each(firmware, function(i, item) {
    htmlString = htmlString + "<li>" + item.Request;
    });

    $('#topFirmware').html(htmlString + "</ol>");
    htmlString = "<ol>";
    $.each(exe, function(i, item) {
    htmlString = htmlString + "<li>" + item.Request;
    });

    $('#exe').html(htmlString + "</ol>");

$.fn.digits = function(){
    return this.each(function(){
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})

</script>

我对PHP编程很新,所以不确定排列和语法。如果出现问题并且您需要更多信息,请纠正我并指导我。在此先感谢!!

2 个答案:

答案 0 :(得分:1)

您无法通过脚本标记直接加载(和使用)JSON数据,请尝试此操作:

$.getJSON('/json/softwarelogs.js', function(data) {
   var htmlString = "<ol>";
   $.each(data.firmware, function(i, item) {
    htmlString = htmlString + "<li>" + item.Request;
    });

    $('#topFirmware').html(htmlString + "</ol>");
    htmlString = "<ol>";
    $.each(exe, function(i, item) {
    htmlString = htmlString + "<li>" + item.Request;
    });

    $('#exe').html(htmlString + "</ol>");

    $.fn.digits = function(){
        return this.each(function(){
            $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
    })
});

答案 1 :(得分:0)

假设您的json保存在像

这样的变量中

注意: - 如果它是一个简单的字符串,那么您可以使用JSON.parse(jsonString);更改为json

var jsData={
"firmware": [
    {
        "Request": "/Firmware/samsung",
        "Count": "2954"
    },
    {
        "Request": "/Firmware/apple",
        "Count": "2954"
    }
],
"exe": [
    {
        "Request": "/applications/appstore.exe",
        "Count": "4482"
    }
]    
};

现在更改以下声明

$.each(firmware, function(i, item)

$.each(jsData.firmware, function(i, item)