我来自 javascript 的外部函数在 html 之前没有加载

My external function from javascript doesnt load before html

我正在使用 INTEL XDK 和 bootstrap 大型机开发移动应用程序。 我有 Html 代码和一些具有 运行 功能的外部 js 文件。 由于某种原因,JS 文件中的函数 dosmth() 不会在 HTML 之前加载,所以它没有给我任何结果。 (该函数应该 return 一个字符串数组)。 有人能告诉我我的代码有什么问题吗?我错过了什么。

HTML 标题包含文件。

      <script src="js/file.js"></script>

这是在我的 HTML 文件上调用函数的代码。

    <h4>
        <script type="text/javascript">
              document.write(dosmth());
         </script>
    </h4>

js文件中方法的代码

        function getCities()
          {
            var url = file.api + "name";
             console.log(url);
             $.getJSON(url).done(function(response){
                              if (!response.length) {
                              console.warn("Empty");
              }
                          file.name = response;
                        $('body').trigger('name-data');
                           console.log(response);
                           return (response);
                    }.fail(function(data, status, error){
                       console.error("Something went wrong");
                                  });
                     }

也许这有帮助。

首先,确保 HTML 标记是可选的。例如,为这个 h4.

指定一个 id
<h4 id="cities"></h4>

您还需要等待文档加载完成再调用JS函数:

<script type="text/javascript">
     window.onload = function() {
         getCities();
     );
</script>

我们不返回任何内容,而是更新 h4

function getCities()
{
    var url = file.api + "name";
    $.getJSON(url).done(function(response){
        if (!response.length) {
            console.warn("Empty");
        }
        // don't know what these two lines are meant to do
        file.name = response;
        $('body').trigger('name-data');
        // update the h4 element
        $('#cities').html(response);
        // the next line was missing a ")" before ".fail"
    }).fail(function(data, status, error){
        console.error("Something went wrong");
    });
}