웹 워커로부터 AJAX 요청을 할 수 있습니까?
웹워커에서 jQuery를 사용할 수 없는 것 같습니다. 사용할 수 있는 방법이 있어야 한다는 것을 알고 있습니다.XMLHttpRequest
하지만 제가 이 답을 읽을 때는 그것이 좋은 선택이 아닌 것 같습니다.
물론 웹 워커 내부에서 AJAX를 사용할 수 있습니다. AJAX 호출은 비동기식이므로 콜백을 사용해야 합니다.
여기가 바로ajax
웹워커 내부에서 서버를 누르고 AJAX 요청을 수행하는 데 사용하는 기능:
var ajax = function(url, data, callback, type) {
var data_array, data_string, idx, req, value;
if (data == null) {
data = {};
}
if (callback == null) {
callback = function() {};
}
if (type == null) {
//default to a GET request
type = 'GET';
}
data_array = [];
for (idx in data) {
value = data[idx];
data_array.push("" + idx + "=" + value);
}
data_string = data_array.join("&");
req = new XMLHttpRequest();
req.open(type, url, false);
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.onreadystatechange = function() {
if (req.readyState === 4 && req.status === 200) {
return callback(req.responseText);
}
};
req.send(data_string);
return req;
};
그런 다음 작업자 내부에서 다음 작업을 수행할 수 있습니다.
ajax(url, {'send': true, 'lemons': 'sour'}, function(data) {
//do something with the data like:
self.postMessage(data);
}, 'POST');
웹 작업자를 통해 너무 많은 AJAX 요청이 전달되는 경우 발생할 수 있는 몇 가지 위험에 대해 이 답변을 읽어보는 것이 좋습니다.
JSONP를 사용하는 다른 도메인의 서비스를 호출하려는 경우 스크립트 가져오기 기능을 사용할 수 있습니다.예:
// Helper function to make the server requests
function MakeServerRequest()
{
importScripts("http://SomeServer.com?jsonp=HandleRequest");
}
// Callback function for the JSONP result
function HandleRequest(objJSON)
{
// Up to you what you do with the data received. In this case I pass
// it back to the UI layer so that an alert can be displayed to prove
// to me that the JSONP request worked.
postMessage("Data returned from the server...FirstName: " + objJSON.FirstName + " LastName: " + objJSON.LastName);
}
// Trigger the server request for the JSONP data
MakeServerRequest();
다음과 같은 유용한 팁을 찾았습니다. http://cggallant.blogspot.com/2010/10/jsonp-overview-and-jsonp-in-html-5-web.html
Fetch API에서 JS 함수 fetch()를 사용하면 됩니다.또한 CORS 바이패스 등과 같은 다양한 옵션을 설정할 수 있습니다(따라서 스크립트 가져오기와 동일한 동작을 수행하지만 약속을 사용하는 훨씬 깨끗한 방법으로 수행할 수 있습니다).
코드는 다음과 같습니다.
var _params = { "param1": value};
fetch("http://localhost/Service/example.asmx/Webmethod", {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify(_params )
}).then(function (response) {
return response.json();
}).then(function (result) {
console.log(result);
});
웹 서비스의 web.config는 다음과 같습니다.
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
언급URL : https://stackoverflow.com/questions/20663353/is-it-feasible-to-do-an-ajax-request-from-a-web-worker
'sourcecode' 카테고리의 다른 글
시스템 유휴 시간 가져오기 (0) | 2023.09.01 |
---|---|
비'@objc' 메서드가 '@objc' 프로토콜의 선택적 요구 사항을 충족하지 않습니다. (0) | 2023.09.01 |
Angular2 동적 변경 CSS 속성 (0) | 2023.09.01 |
평평하지 않은 인덱스를 반환하는 numpy 배열의 Argmax (0) | 2023.09.01 |
Javascript에서 이중 백슬래시를 단일 백슬래시로 바꾸기 (0) | 2023.09.01 |