emscripten-core / emscripten-core/emscripten
how could get the "responseText" when request "XMLHttpRequest"
- Dominant language
- C++
- Stars
- 27.6k
- Forks
- 3.6k
- Avg merge
- 1d 1h
- Merged PRs (30d)
- 105
Description
emscripten version: 3.1.7
i am trying to "XMLHttpRequest" communication.
and using Post Method.
try 1)
use EM_ASM_PTR
```
char* EmscriptenStr = (char*)EM_ASM_PTR({
var str = UTF8ToString($0);
var xhr = new XMLHttpRequest();
xhr.open('POST', str, true);
xhr.setRequestHeader("Content-Type", "text/plain; charset=UTF-8;");
xhr.send("");
xhr.onreadystatechange=function()
{
if (xhr.status==200)
{
console.log(xhr.responseText);
var lengthBytes = lengthBytesUTF8(xhr.responseText)+1;
var stringOnWasmHeap = _malloc(lengthBytes);
stringToUTF8(jsString, stringOnWasmHeap, lengthBytes);
return stringOnWasmHeap;
}
else
{
console.log(xhr.responseText +"\n");
console.log(xhr.status + "cannot find server\n")
}
}
}, URL.c_str());
std::string return_value = EmscriptenStr;
printf("UTF8 string says: %s\n", EmscriptenStr);
free(EmscriptenStr); // Each call to _malloc() must be paired with free(), or heap memory will leak!
return return_value;
```
but, error message : use of undeclared identifier 'var';
try 2)
use emscripten/val.h
```
EM_JS(void, Return_Callback, (EM_VAL val_handle), {
var value = Emval.toValue(val_handle);
value.onreadystatechange = function()
{
if (value.readyState==4 && value.status==200)
{
var msg = value.responseText;
console.log(msg);
}
};
});
std::string FunctionLua::RequestHistoryIndividualTag(std::string URL)
{
val xhr = val::global("XMLHttpRequest").new_();
xhr.call("open", std::string("POST"), std::string(URL));
xhr.call("setRequestHeader", std::string("Content-Type"), std::string("text/plain; charset=UTF-8;"));
std::string return_value = "";
xhr.call("send", std::string(""));
Return_Callback(xhr.as_handle());
return_value = xhr["responseText"].as();
printf("readyState:%d, status:%d, responseText:%s\n",xhr["readyState"].as(),xhr["status"].as(), return_value.c_str());
return return_value;
}
```
second try failed too,
i check the data arrived.
but it can't receive responseText data.
Contributor guide
Assessment
This issue has not been assessed yet.