代码之家  ›  专栏  ›  技术社区  ›  Arnis Lapsa

Jquery AJAX删除问题

  •  1
  • Arnis Lapsa  · 技术社区  · 14 年前

    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" language="javascript">
       var deleteUser = function () {
       var id = this.id.split('lnk_delete_user_')[1];
       console.log(id); //prints frickin "2"
       $.ajax({
         type: "DELETE", url: '<%= Url.Action("DeleteUser") %>', data: "id=" + id,
         success: function (data) {
         window.location.href = '<%= Url.Action("Users") %>'
        }
       });
       };
       $(function ($) { $("a[id^=lnk_delete_user_]").confirm().click(deleteUser); });
    </script>
    

    服务器端未收到“id”参数。怎么了?

    $.ajax(...) id等于2。

    data: "id="+id, data: {id:id}

    我的动作是这样的:

    [HttpDelete]
    [Authorize(Roles="admin")]
    public ActionResult DeleteUser(string id){
      //does not get even so far
    }
    
    3 回复  |  直到 14 年前
        1
  •  4
  •   Nick Craver    14 年前

    目前,您需要发布而不是删除,如下所示:

    $.ajax({
      type: "POST", 
      url: '<%= Url.Action("DeleteUser") %>', 
      data: { id: id },
      success: function (data) {
        window.location.href = '<%= Url.Action("Users") %>'
      }
    });
    

    jQuery在1.4.4之前不会正确序列化DELETE请求的数据参数, there is already a fix in place for this …因此,如果您可以等待jQuery 1.4.4错误修复版本,那么应该解决这个问题。

        2
  •  2
  •   Darin Dimitrov    14 年前

    脚本中未定义id javascript变量。另外,我建议您使用数据哈希而不是字符串连接,因为这样可以确保正确的编码:

    $.ajax({
        type: 'DELETE', 
        url: '<%= Url.Action("DeleteUser") %>', 
        data: { id: '123' },
        success: function (data) {
            window.location.href = '<%= Url.Action("Users") %>';
        }
    });
    

    控制器操作如下所示:

    [HttpDelete]
    public ActionResult DeleteUser(string id)
    {
        throw new NotImplementedException();
    }
    

    问题似乎来自于您正在使用jquery: http://code.jquery.com/jquery-latest.min.js

    当您从google CDN中包含它时,它工作得很好:

    http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js

        3
  •  0
  •   MaX    14 年前

    $.ajax({
    type: 'DELETE', 
    url: '<%= Url.Action("DeleteUser") %>', 
    data: { id: <%= id %> },
    success: function (data) {
        window.location.href = '<%= Url.Action("Users") %>';
    }});