1

JScript.js 文件

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 文件的完整代码

4

2 回答 2

1

我看到的一个明显问题是你正在将你的程序嵌入$(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;
        }
    })
}
于 2012-05-28T20:19:13.977 回答
0

您似乎异步加载脚本,但同步调用它。输出 HTML 将在哪里Page.ClientScript.RegisterStartupScript登陆?

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

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

或者直接执行,即去掉Helloworld.

于 2012-05-28T20:25:36.177 回答