繁体   English   中英

如何在dart中调用html文件中的方法?

[英]How to call method from html file in dart?

我想使用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文件中一样。

您可以使用通过BrowserClient添加对XMLRequest的支持的http包。

这是一个例子:

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM