加载Javascript .js(调用Web服务)Asynchrosusly进入页面

时间:2012-05-28 20:01:40

标签: javascript asp.net ajax

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;
        }
    })
});

}

Default.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>

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

2 个答案:

答案 0 :(得分:1)

我看到的一个明显问题是您将$(document).ready()嵌入Helloworld()例程中。相反,请取出$(document).ready()。假设您正在调用RegisterStartupScript,您希望在文档准备就绪时执行该Javascript,从而使$(document).ready()多余并且可能是您的问题,因为$(document).ready()可能已经在您{之前调用过Helloworld() {1}}例程被触发。

因此,请转到以下代码,看看是否有帮助:

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;
        }
    })
}

答案 1 :(得分:0)

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

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

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

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