JSON received but error for "Resource interpreted as Script but transferred with MIME type application/json"
Im parseing a JSON file and add the data to a HTML
dropdown , code as follows,
$.getJSON(
"http://mobile.icta.lk/services/railwayservice/开发者_如何学PythongetAllLines.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 :
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.
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>
精彩评论