简体   繁体   English

纯 JS 同步 AJAX 调用远程站点

[英]Pure JS synchronous AJAX call to a remote site

This is what I got:这是我得到的:

function fetchJson(url, method, params) {
    var request,
        method = method || 'GET',
        params = params || null;

    if (window.XMLHttpRequest) {
        request = new window.XMLHttpRequest();
    } else {
        try {
            request = new ActiveXObject("MSXML2.XMLHTTP");
        } catch (ex) {
            return null;
        }
    }

    request.open(method, url, false);
    request.send(params);

    if (request.readyState === 4 && request.status === 200)
        return JSON.parse(request.responseText);

    return null;
}

This is supposed to fetch a json synchronously .这应该是同步获取 json 的。

However, when I run this in Opera 12 to fetch a Twitter search Json I get an unhandled NETWORK_ERR thrown.但是,当我在 Opera 12 中运行它以获取 Twitter 搜索 Json 时,我得到了一个未处理的 NETWORK_ERR 抛出。

Is it possible to write a pure-JS synchronous ajax function that can fetch json from any location?是否可以编写一个可以从任何位置获取 json 的纯 JS 同步 ajax 函数?

Calls using XMLHttpRequest are subject to the Same Origin Policy , which prevents cross-origin calls unless both the server and browser support Cross-Origin Resource Sharing ( most browsers do , although IE8 and IE9's support is broken, requiring use of the MS-specific XDomainRequest object) and the server grants access to the origin of your document.使用XMLHttpRequest调用受同源策略的约束,除非服务器和浏览器都支持跨域资源共享大多数浏览器都支持,但 IE8 和 IE9 的支持被破坏,需要使用 MS 特定的XDomainRequest ,否则它会阻止跨域调用对象)并且服务器授予对文档来源的访问权限。

Absent CORS, there is no direct synchronous solution.如果没有 CORS,就没有直接的同步解决方案。 You'd have to go indirectly through your own server.您必须通过自己的服务器间接访问。

If the twitter feed supports JSONP , though, you can use that, which is asynchronous.但是,如果 twitter 提要支持JSONP ,您可以使用它,它是异步的。 Asynchronous requests are generally best in any case.在任何情况下,异步请求通常都是最好的。

So summarizing the above, the answer to所以总结以上,答案

Is it possible to write a pure-JS synchronous ajax function that can fetch json from any location?是否可以编写一个可以从任何位置获取 json 的纯 JS 同步 ajax 函数?

...is "Yes, if the server supports CORS and allows requests from your origin, and you're using a browser supporting CORS; no if not, you have to go through your own server or do an asynchronous request." ...是“是的,如果服务器支持 CORS 并允许来自您的源的请求,并且您使用的是支持 CORS 的浏览器;否则,您必须通过自己的服务器或执行异步请求。”

In this case, You have to use jsonp... CrossDomain communication...在这种情况下,您必须使用 jsonp...CrossDomain 通信...

I made pure javascript function for you... You can have a look and free to use it我为你制作了纯javascript函数...你可以看看并免费使用它

https://github.com/toosha01/ajax-javascript https://github.com/toosha01/ajax-javascript

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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