2012-10-13 97 views
1

我是jQuery的新手。我需要在一段时间后调用方法。需要调用jQuery ajax页面方法

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

它说,未捕获的ReferenceError:未定义SetTime2。 什么是正确的语法?谢谢。

+0

是否有页面上的任何JS错误。如果您使用的是Chrome浏览器,请点击重新加载并查看是否有错误。 –

+0

删除围绕函数SetTime2方法的括号后尝试 –

回答

2

改成这样:

$(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. 你只是需要确定你的SetTime2()声明中的正常功能。周围没有人。

  2. 此外,你不想传递一个字符串到setTimeout(),你想传递一个实际的函数引用没有引号或parens。

注意:你也可以做到这一点使用匿名函数:

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