开发者

problem using HTML5 for Cross-origin resource sharing

开发者 https://www.devze.com 2023-01-10 23:49 出处:网络
I am new to this site and had been successfully using the \"HTML5\" Cross-origin resource sharing (CORS) to POST data to my server. I just recently tried to include GETs in that as we are trying to ha

I am new to this site and had been successfully using the "HTML5" Cross-origin resource sharing (CORS) to POST data to my server. I just recently tried to include GETs in that as we are trying to have all of our communications be non-reliant on a JavaScript library. In doing so I have run into an odd issue that seems somewhat fixable for Firefox but is still misbehaving in all the WebKit browsers. Essentially anything that returns a status of <200 or >300 is just co开发者_StackOverflow社区ming in as a status of 0. This makes it next to impossible to do error handling.

For Firefox, I am able to put a random string on the end of the request to prevent it from being cached; thereby fixing the 304s at least. This however does not work at all for me in Chrome/Safari. Here is a sample of my code:

xhr_request: function(type,url, data, callbacks, form){
    var form = (typeof(form)!=="undefined")?form:null;
    var xhr = new XMLHttpRequest();
    var response;
    data = com.ticommunity.obj_to_string(data);
    xhr.open(type, url, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("X-TxId", com.ticommunity.keyGen());
    xhr.withCredentials = true;
    xhr.send(data);
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                response = xhr.responseText;
                com.ticommunity.comm.request_callback(response, callbacks, form);
            }else{`//****this is where the 0 Status keeps coming up***`
                response = xhr.status;
                com.ticommunity.comm.request_callback(response, callbacks, form);
            }
        }
    }
}

Has anyone else run into something similar and come up with a work-around? Am I just doing something stupid on my end? Any help is greatly appreciated.

EDIT: I realized the 0 is what is supposed to happen per the spec, but I REALLY need to be able to trap for these situations and do some other handling.


I haven't seen this issue specifically, but I wonder if you'd have better luck using a different xhr event, such as xhr.onload. You can trust onload to fire on successful responses, so there's no need to check xhr.status. Here's a complete list of events if you need to trap on something else:

http://www.w3.org/TR/XMLHttpRequest2/#events

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号