我想使用Dart将xmlhttprequest发送到我的服务器。我有一个html
文件,实际上可以实现它。有没有办法从dart中的html文件运行方法?或者也许这个代码可以用dart重写?作为回应,我得到一个包含两个字段的对象的JSON
:名称和持续时间。
// my html file
<script>
function createCORSRequest() {
let xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open('GET', 'http://localhost:8080/sounds', true);
} else {
if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open('GET', 'http://localhost:8080/sounds');
} else {
xhr = null;
}
}
return xhr;
}
function makeCorsRequest() {
var request = createCORSRequest();
if (!request) {
alert('CORS not supported');
return;
}
// here I get the names of the objects
request.onload = function () {
var movies = request.response;
for (const movie of movies) {
console.log(movie.movieName)
}
};
request.onerror = function () {
alert("Request failed");
};
request.responseType = 'json';
request.send();
}
</script>
我从服务器获得的JSON示例:
[
{
"movieName": "Dog and the main Dogger",
"duration": "3:30:03"
},
{
"movieName": "Hunger Games",
"duration": "3:30:03"
},
{
"movieName": "Robot Chicken",
"duration": "3:30:01"
},
{
"movieName": "Moskovskaya techka",
"duration": "3:30:03"
},
{
"movieName": "Terminator",
"duration": "3:30:03"
}
]
我想从Dart中的JSON
获取名称(movieName字段),就像在我的HTML
文件中一样。
你可以使用http包,用XMLRequest
添加对BrowserClient
s的支持。
这是一个例子:
var browser = BrowserClient();
var response = await browser.get('http://localhost:8080/sounds');
var body = response.body; //Here you can use 'json.encode' from the `dart:convert` package to parse the json list.