【问题标题】:getting data as the page loads在页面加载时获取数据
【发布时间】:2011-11-13 02:10:14
【问题描述】:

我正在尝试在 DOM 中准备好元素后取回数据。我正在尝试使用 JQUERY 中的加载函数,但我收到一条消息 .load() 不是函数。

在页面加载期间使用 ajax 获取元素(在我的情况下为 div)的数据时,是否有最佳实践?我正在使用 ASP.NET 并在后面的代码中调用 webmethod。

这是我的 ajax/jquery 代码:

$(document).ready(function () {

      $(function () {

          $("[id$=divArea]").load()(function () {

              $.ajax({
                  type: "POST",
                  url: "apage.aspx/Role",
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  async: false,
                  success: function (response) {
                      alert("got data from Role");
                  },
                  error: function (data) {
                      alert("failed to get data from Role");
                  }

              });               

          });

});

谢谢。

【问题讨论】:

  • .load 仅适用于实际加载某些内容的元素,例如 iframe 图像和窗口。你到底想做什么?
  • 是否可以在匹配多个元素的 jQuery $object 上使用$object.load()

标签: asp.net jquery


【解决方案1】:

我认为是代码本身的问题,试试这样的代码

$(document).ready(function (){

    $("[id$=divArea]").load('apage.aspx/Role',function(response, status, xhr) {
        if (status == "error") {
             var msg = "Sorry but there was an error: ";
             $("#error").html(msg + xhr.status + " " + xhr.statusText);
        })

});

【讨论】:

    【解决方案2】:

    $(document).ready() 用于在 DOM 准备好后调用代码 - 因此,如果我理解正确,您不需要包含 $("[id$=divArea]").load()(function () {

    它应该像这样工作:

    $(document).ready(function () {
    
      $(function () {
    
              $.ajax({
                  type: "POST",
                  url: "apage.aspx/Role",
                  data: "{}",
                  contentType: "application/json; charset=utf-8",
                  dataType: "json",
                  async: false,
                  success: function (response) {
                      alert("got data from Role");
                  },
                  error: function (data) {
                      alert("failed to get data from Role");
                  }
    
              });               
    
          });
    
    });
    

    顺便说一句 - 这可能是一个粘贴错误,但您在发布的代码中也省略了 $(document).ready 关闭 });

    【讨论】:

    • 经过反思,您甚至不需要 $(function () {});包装您的 ajax 调用 - 您可以直接在 $(document)ready(function(){}) 中进行 ajax 调用
    猜你喜欢
    • 2020-02-10
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-10
    相关资源
    最近更新 更多