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>

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 ファイルを非同期的にロードするための完全なコードです。

4

2 に答える 2

1

私が目にする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 に答える