JSON received but error for “Resource interpreted

2019-08-05 09:55发布

Im parseing a JSON file and add the data to a HTML dropdown , code as follows,

$.getJSON(
    "http://mobile.icta.lk/services/railwayservice/getAllLines.php?lang=en&jsoncallback=?",
    function(data) {

        var $s = $('.txtline').empty();

        // the actual contents of this loop will be
        // specific to the data
        for (var k in data) {
            $('<option></option>')
                .val(data[k].value)
                .text(data[k].text)
                .appendTo($s);
        }
    }
)

Im getting a error as,

Resource interpreted as Script but transferred with MIME type application/json.

getAllLines.php:2Uncaught SyntaxError: Unexpected token :

标签: jquery html json
2条回答
男人必须洒脱
2楼-- · 2019-08-05 10:32

The problem is that this remote server returns JSON, not JSONP. It returns:

{"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]}

instead of:

someCallbackName({"lines":[{"line":"COLOMBO - BADULLA"},{"line":"COLOMBO - MATALE"},{"line":"COLOMBO - PUTTLAM"},{"line":"COLOMBO - THANDIKULAM"},{"line":"COLOMBO - TALAIMANNAR"},{"line":"COLOMBO - BATTICALOA"},{"line":"COLOMBO - TRINCOMALEE"},{"line":"COLOMBO - MATARA"},{"line":"COLOMBO - AVISSAWELLA"},{"line":"COLOMBO - MIHINTALE"}]})

You will not be able to consume a remote domain using AJAX unless this remote resource supports JSONP.

查看更多
放我归山
3楼-- · 2019-08-05 10:33

Here is a little script:

<?php
    // file url: http://localhost/remote-json-proxy.php
    $url = 'http://mobile.icta.lk/services/railwayservice/getAllLines.php';
    $qsa = '?';
    foreach($_GET as $n => $v) {
        if($n != 'callback') {
            $qsa .= '&' . $n . '=' . rawurlencode($v);
        }
    }
    $json = file_get_contents($url . $qsa);
    echo sprintf('%s(%s);', $_GET['callback'], $json);
?>

Usage:

<!-- file url: http://localhost/test.htm -->
<script type='text/javascript'>
    $.getJSON('remote-json-proxy.php?lang=en&this=that&callback=?', function(data) {
        console.log(data);
    })
</script>
查看更多
登录 后发表回答