2011-05-28 71 views
0

这里是jQuery代码:jQuery的POST方法不起作用

$(function() { 
      $("#personCreate").click(function() { 

       var person = getPerson(); 

       // poor man's validation 
       if (person == null) { 
        alert("Specify a name please!"); 
        return; 
       } 

       // take the data and post it via json 
       $.post("banner/save", person, function (data) { 
        // get the result and do some magic with it 
        alert("Post"); 
        var message = data.Message; 
        $("#resultMessage").html(message); 
       }); 
      }); 
     }); 

控制器:

  [HttpPost] 
      public ActionResult Save(PersonModel person) 
      { 
       string message = string.Format("Created {0} in the system",person.Name); 
       return Json(new PersonViewModel {Message = message }); 
      } 

当我按一下按钮没有任何行动。该帖子从不指向控制器。

回答

1

这样的硬编码的URL始终看起来很可疑:

$.post("banner/save", ... 

当使用URL确保你总是使用URL佣工生成它们:

$.post("@Url.Action("save", "banner")", ... 

其他的事情,你应该寻找的是控制台选项卡FireBug,因为它将为您提供有关AJAX请求的有价值的信息:正在向服务器发送什么以及正在接收什么,并希望指出错误。

另外你还没有表现出这种getPerson()功能,但在对象被张贴在一天结束的时候应该是这样的:

var person = { prop1: 'value 1', prop2: 'value 2', .... }; 

其中明显PROP1,PROP2,...是PersonModel的性质。

您应该注意的另一件事是这#personCreate按钮。如果这是一个提交按钮或一个锚链接,你应该确保在点击处理程序返回false取消默认的动作或你的Ajax可能从来没有执行时间:

$("#personCreate").click(function() { 

    // ... the AJAX request here 

    return false; 
}); 
0

我不知道究竟如何您的路由设置完成,但您没有以正确的方式通过person变量。

如果您需要发送banner/save/#(其中#person值),你需要

$.post("banner/save/" + person, function (data) { 

如果您需要(在#同上)发送banner/save?person=#你需要

$.post("banner/save", {person: person}, function (data) { 

如果您只要传递值,jQuery就会在其上运行jQuery.param,这将导致发送到服务器的空字符串。显然这不会叫你的控制器。

0

也许问题是事件没有正确地附加到按钮上:你试过做这样的事情吗?

可以肯定的是,事件被触发,你应该使用Firebug

$(document).ready(function() { 
      $("#personCreate").click(function() { 

       var person = getPerson(); 

       // poor man's validation 
       if (person == null) { 
        alert("Specify a name please!"); 
        return; 
       } 

       // take the data and post it via json 
       $.post("banner/save", person, function (data) { 
        // get the result and do some magic with it 
        alert("Post"); 
        var message = data.Message; 
        $("#resultMessage").html(message); 
       }); 
      }); 
     }); 
+1

使用'$(函数(){})'是'$(文件)。就绪的快捷方式()' – lonesomeday 2011-05-28 14:08:26

+0

我感谢名单不知道! :) – 2011-05-28 14:09:29