-3

我被困住了,(JavaScript 新手)所以我不想使用 Jquery。但是我确实需要在 JavaScript 中执行以下操作。这是一个简单的获取/解码和循环数组。

<?php 
    $url = "http://data.police.uk/api/forces"; // Make the url
    $c = file_get_contents($url); // Get JSON
    $forces = json_decode($c,true);  // Decode JSON

    foreach( $forces as $obj ) { 
    echo $obj['id'];
                 } ?>  <!-- End Loop -->

谢谢你们的支持,你们太棒了!

4

2 回答 2

1

That API supports JSONP:

http://data.police.uk/api/forces?callback=your_callback

So you can just create a <script> tag:

var script = document.createElement('script');
script.src = 'http://data.police.uk/api/forces?callback=your_callback';
script.type = 'text/javascript';

document.head.appendChild(script);

And register a global callback function that will run when that script loads:

window.your_callback = function(data) {
    for (var i = 0; i < data.length; i++) {
        ...
    }
};

But jQuery is nicer:

$.getJSON('http://data.police.uk/api/forces?callback=?', function(data) {
    ...
});
于 2013-05-10T21:24:46.993 回答
0

它本质上是在编写一个解析器——但你可能想看看这个博客:

http://www.bennadel.com/blog/1780-Using-Javascript-s-Function-Constructor-To-Deserialize-JSON-Data.htm

于 2013-05-10T21:18:08.433 回答