【问题标题】:MVC 4 Ajax call is not made未进行 MVC 4 Ajax 调用
【发布时间】:2014-08-05 21:24:23
【问题描述】:

这几天我一直在尝试解决我的应用程序中的一个问题,但我不知道发生了什么。

我正在开发一个 MVC 4 应用程序。我有一个视图,其中有一个 div,我使用在 $(function() { ... }); 上执行的 ajax 调用加载了更多 html。该ajax调用工作正常。

当我进行第二次 ajax 调用时,问题就开始了。我粘贴下面的代码:-

在主视图中:-

<div class="body" id="loadedData">

</div>

<script type="text/javascript" charset="utf-8">
   $(function(){
      loadData("@Url.Action("Authorizations","User", new { id = Model.ID })");
   });

   function loadData(url){
      $.ajax({
        type: 'GET',
        url: url,
        success: function (data) {
            $("#loadedData").html(data);
        }
    });
   }
</script>

在 div 中加载的局部视图是这样的:

@if (ViewBag.UserAuths != null){
  <table>
      <tr>
          <th>
              Operations
          </th>
          <th></th>
      </tr>
      @foreach (var prod in ViewBag.UserAuths){
          <tr>
              <td>
                  @prod[0]
              </td>
              <td>
                 <a href="" onclick="loadData(@Url.Action("RevokeAccess", "User", new {    id = ViewBag.UserID, op = Int32.Parse(prod[1])}));">Remove</a>
              </td>
          </tr>
      }
  </table>
 }

当我单击由 ajax 加载的 HTML 中的链接时会出现问题(删除)。当我单击时,页面“闪烁”但没有任何反应。我在 UserController 的 RevokeAccess 函数中设置了一个断点,它永远不会停止。

请帮忙!

编辑:

还有一件事,当我单击链接时,在 Chrome 控制台中显示“未捕获的语法错误:意外的令牌”消息,但它很快消失了,我不知道为什么。

【问题讨论】:

  • 将 event.preventDefault() 添加到加载函数中
  • 指定您在 ajax 调用中传递的数据类型,例如 dataType: "json"
  • 当你点击锚点时它是否在调用loaddata??
  • 在 ajax 调用中给出数据类型和内容类型...

标签: javascript jquery html ajax asp.net-mvc


【解决方案1】:

当您使用 jQuery 时,不要使用 内联事件。使用 jQuery 绑定点击事件。当您获取部分视图时,您可以使用.load(),这要简单得多。

脚本

<script type="text/javascript">
   $(function(){
       $("#loadedData").load("@Url.Action("Authorizations","User", new { id = Model.ID })");      

       $("#loadedData").on('click', '.anchor', function(event){
            event.preventDefault();//Stop default action  
            $("#loadedData").load(
                $(this).data('url'),  //Url
                { id: $(this).data('id'), op : $(this).data('op')}, //Parameters
                function(){
                    //Perform any action if any
                }
            );
       })
   });

</script>

将您的部分更改为

@if (ViewBag.UserAuths != null){
  <table>
      <tr>
          <th>
              Operations
          </th>
          <th></th>
      </tr>
      @foreach (var prod in ViewBag.UserAuths){
          <tr>
              <td>
                  @prod[0]
              </td>
              <td>
                 <a class='anchor' href="#" data-url='@Url.Action("RevokeAccess", "User")' data-id="@ViewBag.UserID" data-op="@Int32.Parse(prod[1])">Remove</a>
              </td>
          </tr>
      }
  </table>
 }

【讨论】:

  • @die8292:很高兴我能帮上忙 :)
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2013-05-17
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多