1

如何将我的 php 数组传递给这个 jquery 代码?我已经尝试过 json_encoding 但无法在我的 jquery 函数中使用它。我的 json 字符串如下所示:

{"1":{"id":"1","league":"england","team1":"Arsenal","team2":"Chelsea"},"2":{"id":"2","league":"spain","team1":"Deportivo","team2":"Real Madrid"}}

JS:

 <script type="text/javascript">
            $(document).ready(function(){
                var shownIds = new Array();
                setInterval(function(){     
                    $.get('livescore_process.php', function(data){
                        for(i = 0; i < data.length; i++){
                            if($.inArray(data[i]["id"], shownIds) == -1){
                                if(data[i]["league"]=="england"){
                                    $("#eng").append("id: " + data[i]["team1"] + " [ "+data[i]["team1"]+ " - "+data[i]["team1"]+" ]"+ data[i]["team2"] +"<br />");
                                }
                                shownIds.push(data[i]["id"]);
                            }
                        }
                    });
                }, 3000);
            });
        </script>
4

1 回答 1

0

尝试$.getJSON代替$.get并使用 php json_encode

$.getJSON('livescore_process.php', function(data){...

但是响应数据不是数组而是 json 对象,因此要处理它,您可以尝试:

$.each(data, function (index, item) {
    if (item.hasOwnProperty('id')) {
        if (item.league == "england") {
            $("#eng").append("id: " + item.team1 + " [ " + item.team1 + " - " + item.team1 + " ]" + item.team2 + "<br />");
        }
        shownIds.push(item.id);

    }
});

jsfiddle

于 2013-05-05T16:22:42.503 回答