问题
I am trying to use the youtube "api" for search
http://suggestqueries.google.com/complete/search?q=INPUT&client=firefox&hl=cs
but the site returns with a content-disposition: attachment; header and downloads a file (f.txt) with a JSON response.
Is there a way to obtain the JSON as a string in javascript?
(I am sure there is. Youtube has to do it somehow)
jQuery-less please if possible.
回答1:
Not sure how you are trying to access API in browser directly. It will not work that way. Make an AJAX call to the same API and you will get error message as,
XMLHttpRequest cannot load http://suggestqueries.google.com/complete/search?q=india&client=firefox&hl=cs. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://null.jsbin.com' is therefore not allowed access.
Reason?
Because this API is meant for google internal products so it will not work normally.
Cross-domain restriction is relatively common and making a JSONP based request can solve this.
Try this,
$.getJSON("http://suggestqueries.google.com/complete/search?callback=?",
{
"hl":"en",
"jsonp":"suggestCallBack",
"q":'ind', // query term
"client":"firefox"
});
suggestCallBack = function (data) {
console.log(data);
};
Now this is a JQuery based solution but AJAX call can be made easily without JQuery also but I never tried making JSONP call without JQuery.
来源:https://stackoverflow.com/questions/41314677/ajax-cant-load-url