XMLHttpRequest to webservice not working in web worker

删除回忆录丶 提交于 2019-12-03 21:45:25

Ok I was really stupid here. The reason why I was getting the

 DOMException: INVALID_STATE_ERR


was because according to W3 documentation the xhr.status attribute throws an exception if xhr.readyState has an invalid value:

    Exceptions on retrieval
    DOMException  INVALID_STATE_ERR exception SHOULD be raised if this attribute is accessed when readyState has an inappropriate value. 


I had an invalid xhr.readyState since I did not specify a full path to the webservice I am calling. The full path to the webservice is needed because the webworker runs in the separate Blob file created "on the fly".

Anyway, below is the webwoker code with working webservice call script:

<script id="worker" type="javascript/worker">

    self.onmessage = function (e) {
        var param = e.data;
        var url="http://localhost:54071/WebServices/wsSProgress.asmx/GetSpecProgressTable";
        var data=getSpecData(param.detailLvl,param.startWeek,param.endWeek,param.mkt,url)
        self.postMessage(data);
    }; 
    function getSpecData(detailLvl, startWeek, endWeek, mkt, url) {
        var params = { "detailLvl": detailLvl, "startWeek": startWeek, "endWeek": endWeek, "mkt": mkt };
        var xhr;
        try {
            xhr = new XMLHttpRequest();
            xhr.open('POST', url, false);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var result = JSON.parse(xhr.responseText);
                    self.postMessage(result.d);
                }
            }; 
            xhr.send(JSON.stringify(params));
        } catch (e) {
            self.postMessage('Error occured in XMLHttpRequest: ' + xhr.statusText + '  ReadyState: ' + xhr.readyState + ' Status:' + xhr.status + ' E: ' +e+' Msg:'+e.message);
        }
    }
    </script>

From comments, your exception is:

DOMException: INVALID_STATE_ERR

This means that the contents of your message being posted back to the parent cannot be serialized.

In my experience, this is usually because of circular references or functions present in the object. Without knowing the response that the server is giving, this is as much as I can help you.

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