将 Javascript .js(调用 Web 服务)异步加载到页面中

Load Javascript .js (calls a web service) Asynchrosusly into page

本文关键字:加载 异步 服务 js Javascript 调用 Web      更新时间:2023-09-26

JScript.js file

function Helloworld() {
$(document).ready(function () {
    $.ajax
    ({
        type: "POST",
        url: "Default.aspx/Helloworld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
            document.getElementById('textbox').value = msg.d;
        }
    })
});

}

默认.aspx

    <head runat="server">
    <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
   //Works Fine when I uncomment this 
   <%--  <script src="JScript.js" type="text/javascript"></script>--%>
    <script type="text/javascript" language="javascript">
        (function () {
        var load = document.createElement('script');
        load.type = 'text/javascript';
        load.src = 'JScript.js';
        load.async = true;
        (document.getElementsByTagName('head')[0] ||    document.getElementsByTagName('body')   [0]).appendChild(load);
    })();
    </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <input type="input" id="textbox" />
    </form>
    </body>

默认.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyHelloworld", "<script type='text/javascript'>Helloworld()</script>");
}
[WebMethod(EnableSession = true)]
public static string Helloworld()
{
    return "Hello World";
}
我正在尝试将此 JavaScript 文件异步加载

到页面中,但上面的函数没有执行是异步加载 JavaScript 文件的完整代码

我看到的一个明显问题是你把你的$(document).ready()嵌入到Helloworld()例程中。 相反,取出$(document).ready(). 假定如果您正在调用 RegisterStartupScript,您希望在文档准备就绪时以任何方式执行该 Javascript,从而使$(document).ready()冗余并且可能是您的问题,因为$(document).ready()可能在触发Helloworld()例程之前被调用

因此,更改为以下代码,看看是否有帮助:

function Helloworld() 
{
    $.ajax
    ({
        type: "POST",
        url: "Default.aspx/Helloworld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
            document.getElementById('textbox').value = msg.d;
        }
    })
}

您似乎异步加载脚本,但同步调用它。Page.ClientScript.RegisterStartupScript将在输出 HTML 中的哪个位置着陆?

您需要为动态添加的脚本安装负载处理程序:

    ...
    load.async = true;
    load.onload = function() {
        Helloworld(); // execute when loaded?
    };
    ...

或者直接执行,即删除Helloworld的方法声明。