且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法从服务器读取JSON响应

更新时间:2023-01-02 18:36:54

唯一已知的解决方法是让浏览器认为只有一个来源。最简单的方法是在您自己的服务器上放置一个代理服务器,然后中继到另一台服务器。如果您的服务器在Apache中,则可以使用 mod_proxy (请参阅此问题)。



但请注意,如果其他服务器不允许交叉源请求,则可能违反其政策。如果它是一个大型服务器,它可能会很好地检测到它并禁止你的服务器的IP。

I am working on a web app that sends some data to a website. The website updates the data to its database and returns a json array that replaces my webapp page. I am using ajax for making the query. I need to know how to prevent the overwriting of my webpage. The server is not mine so there is possibly a same origin policy problem.
I have checked the xmlhttp.readystate and xmlhttp.status, they are 4 and 0 respectively. According to some posts on *** the 0 status occurs due to the origin policy but I couldn't get a solution for this because usually the people with this problem had access to changes on the server side programming.
I want to read the json and extract values for my app but if I use the xmlhttp.responseText the server returns a blank string.

Any help is much appreciated.
Thanks

My code:

function sendAndReceive() {

    var xmlhttp;
    xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function () {
        document.getElementById("postevent").innerHTML = "state changed";
        document.getElementById("postevent").innerHTML = "" + xmlhttp.readyState + " " + xmlhttp.status;
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("postevent").innerHTML = "success response";
            document.getElementById("postevent").innerHTML = "this is it" + xmlhttp.responseText;
        }
    }

    var url = "http://simple.ap.ernet.in/api/home/resource.php/resource/node?";
    url += "key=" + document.getElementById("key").value + "&";
    url += "datasetId=" + document.getElementById("datasetId").value + "&";
    url += "localId=" + document.getElementById("localId").value + "&";
    url += "nodeName=" + document.getElementById("nodeName").value + "&";
    url += "nodeDesc=" + document.getElementById("nodeDesc").value + "&";
    url += "lat=" + document.getElementById("lat").value + "&";
    url += "long=" + document.getElementById("long").value;

    document.getElementById("postevent").innerHTML = url;
    xmlhttp.open("POST", url, true);
    xmlhttp.send();
}

The only known workaround is to let the browser think there is only one origin. The easiest is to put a proxy on your own server relaying to the other server. If your own server is in Apache, you may use mod_proxy (see this question).

But note that if the other server doesn't allow cross-origin requests, it's probably against its policy to do that. And if it's a big server, it may very well detect it and ban your server's IP.