简体   繁体   中英

API works in the browser, not JS

This URL outputs JSON in the browser

http://api.sfpark.org/sfpark/rest/availabilityservice?lat=37.7832776731&long=-122.405537559&radius=0.10&uom=mile&response=json

But when I use it with Jquery like below, it seems to output this error

{"STATUS":"ERROR","MESSAGE":"Error while retrieving availability.  Search parameters are not valid. callback is not a valid request parameter. _ is not a valid request parameter.","RESPONSE_SENT_TS":"2014-08-15T12:16:01.455-07:00","REQUEST_RECD_TS":"2014-08-15T12:16:01.450-07:00"}

And this is the code I'm using

var parkingUrl = "http://api.sfpark.org/sfpark/rest/availabilityservice?lat=37.7832776731&long=-122.405537559&radius=0.10&uom=mile&response=json";

$.ajax({
    url:parkingUrl,
    type:'GET',
    dataType:'JSONP',
    success: function(data){
        console.log(data);
    }
});

You are calling the webservice using JSONP. JSONP in jQuery works by adding a callback function to the url, so the url getting called becomes something like

http://api.sfpark.org/sfpark/rest/availabilityservice?lat=37.7832776731&long=-122.405537559&radius=0.10&uom=mile&response=json&callback=callbackfn

The webservice doesn't support this parameter. You have to use type:json and hope the webservice supports CORS.

The error your getting is based on the server-side script.

It maybe that the server may not support JSONP you may want to try:

$.ajax({
    url:parkingUrl,
    type:'GET',
    success: function(data){
       console.log(JSON.parse(data));
    }
});

PHP code for the page

header('Access-Control-Allow-Origin: http://api.sfpark.org');

You could also try if that doesn't work you could try to pull the page info on the server side using PHP, or whatever you are using

$parkingURL = 'http://....';
echo file_get_contents($parkingURL);

According to their API docs, they do in fact support JSONP, you need to add this parameter:

&jsoncallback=callbackFunctionName

To your request url

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM