1

I'm new to jQuery. I need to call the method after some interval.

    $(document).ready(function pageLoad() {
        setTimeout('SetTime2()', 10000);
    });

    (function SetTime2() {
            $.ajax({
                type: "POST",
                url: "MyPage.aspx/myStaticMethod",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    // Replace the div's content with the page method's return.
                    //$("#Result").text(msg.d);
                }
            });
    });

It says, Uncaught ReferenceError: SetTime2 is not defined. What is the correct syntax? Thanks.

4

1 に答える 1

2

Change to this:

$(document).ready(function() {
    setTimeout(SetTime2, 10000);
});

function SetTime2() {
        $.ajax({
            type: "POST",
            url: "MyPage.aspx/myStaticMethod",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                // Replace the div's content with the page method's return.
                //$("#Result").text(msg.d);
            }
        });
}
  1. You need to just define a normal function with your declaration of SetTime2(). No parens around it.

  2. Also, you don't want to pass a string to setTimeout(), you want to pass an actual function reference without the quotes or the parens.

Note: you could also do this using an anonymous function:

$(document).ready(function () {
    setTimeout(function() {
        $.ajax({
            type: "POST",
            url: "MyPage.aspx/myStaticMethod",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                // Replace the div's content with the page method's return.
                //$("#Result").text(msg.d);
            }
        });
    }, 10000);
});
于 2012-10-13T05:15:52.947 に答える