问题描述:

Hi guys i am getting a small error when i am trying to access the foursquare api to find information about a specific restaurant that i am putting in the search.

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

Another thing that i am seeing is that when i put the search int he url to see what comes up i get some crazy code that appears on the page..

the http request results from the browser

here is the code that i have right now...

var fourSquareMain = 'https://api.foursquare.com/v2/venues/search';

var clientID = '?client_id=5LHFTY54EP5VLMYIIVZ0OQGMNZQEM2FUKDPFFA2OJHMO0AVI';

var clientSecret = '&client_secret=2TN3GQBAX4U2GPHGMCUZWS35Y2E5E2Y4NG0YWGVGNMXEPHAW';

var fourSquareVersion = '&v=20130815';

var fourSquareLL = '&ll=' + pointItem.lat() + ',' + pointItem.lng();

var fourSquareQuery = '&query=' + pointItem.name;

var fullFourSquareQuery = fourSquareMain + clientID + clientSecret + fourSquareVersion + fourSquareLL + fourSquareQuery;

var finalFSQuery = fullFourSquareQuery.replace(/ /g, '-');

console.log(finalFSQuery);

网友答案:
  1. The crazy code you are getting is 'what you had requested for' it is the raw json response from foursquare api.

2.It works on the URL but not on the script because when you run the script on your client site you are trying Cross Origin Resource Sharing (CORS) which is not allowed by some APIs for security reasons. To work around this you will need to use JSON-P, a unique trick to allow cross-domain requests. An easy way to do this is to create AJAX requests using jQuery. In your case try to get name of the first venue from the search result

var fourSqrUrl = "https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=XXX&client_secret=YYY&v=20160128"
       $.ajax({
              url: fourSqrUrl,
              success: function(data) {
                $(div1).html('FourSquare Response : ' + data.response.venues[0].name);
                }
              });

` You might have to read a bit about AJAX to get a better idea of how this works and how to read json data.

相关阅读:
Top