AJAX cant load URL

放肆的年华 提交于 2019-12-02 20:30:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!