You've got two ways to go forward:
JSONP
If this API supports JSONP
, the easiest way to fix this issue is to add &callback
to the end of the URL. You can also try &callback=
. If that doesn't work, it means the API does not support JSONP
, so you must try the other solution.
Proxy Script
You can create a proxy script on the same domain as your website in order to avoid the cross-origin issues. This will only work with HTTP URLs, not HTTPS URLs, but it shouldn't be too difficult to modify if you need that.
<?php
// File Name: proxy.php
if (!isset($_GET['url'])) {
die(); // Don't do anything if we don't have a URL to work with
}
$url = urldecode($_GET['url']);
$url = 'http://' . str_replace('http://', '', $url); // Avoid accessing the file system
echo file_get_contents($url); // You should probably use cURL. The concept is the same though
Then you just call this script with jQuery. Be sure to urlencode
the URL.
$.ajax({
url : 'proxy.php?url=http%3A%2F%2Fapi.master18.tiket.com%2Fsearch%2Fautocomplete%2Fhotel%3Fq%3Dmah%26token%3D90d2fad44172390b11527557e6250e50%26secretkey%3D83e2f0484edbd2ad6fc9888c1e30ea44%26output%3Djson',
type : 'GET',
dataType : 'json'
}).done(function(data) {
console.log(data.results.result[1].category); // Do whatever you want here
});
The Why
You're getting this error because of XMLHttpRequest same origin policy, which basically boils down to a restriction of ajax requests to URLs with a different port, domain or protocol. This restriction is in place to prevent cross-site scripting (XSS) attacks.
More Information
Our solutions by pass these problems in different ways.
JSONP
uses the ability to point script tags at JSON (wrapped in a javascript function) in order to receive the JSON. The JSONP page is interpreted as javascript, and executed. The JSON is passed to your specified function.
The proxy script works by tricking the browser, as you're actually requesting a page on the same origin as your page. The actual cross-origin requests happen server-side.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…