简体   繁体   中英

Retreving URL String to generate JSON Object in JavaScript?

I want to access the Yelp API 1.0, I have got for example this URL

http://api.yelp.com/business_review_search?term=burger&location=Los%20Angeles%2A%20CA&ywsid=SECRETKEY

which will give me some Burger Locations in LA in a JSON String.

How can I access this URL in order turn the response into a JS Object?

I know how to create JS Objects, the problem is getting the response from the server.

Here's my code right now: Maybe we can try to start from there:

var url = "http://api.yelp.com/business_review_search?term=burger&location=Los%20Angeles%2A%20CA&ywsid=secretKey" ;


            $.getJSON(url, function(json) {
                alert("JSON Data: " + json.message.text);
            });

You get into the subject of Same-Origin Policy , which simply says that you can't reach a URL from b.com from a.com using ajax in a normal form.

If you use ajax, you should use JSONP , or Access-Control headers. Otherwise, you should use your server as a proxy to send regular HTTP GET and POST to that URL.

Add "&callback=myFunction" to the url. Append a script tag to your document with this url as the source.

var scriptElem = document.createElement('script');
scriptElem.src = url;
document.body.appendChild(scriptElem);

Then make a function in your page called myFunction, and its first argument will be the data returned.

Use $.getJSON() .

Here's an example using yelp:

$.getJSON("http://api.yelp.com/business_review_search?term=burger&location=Los%20Angeles%2A%20CA&ywsid=SECRETKEY&jsoncallback=?", function(json) {
   console.log("JSON Data: " + json);
});

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