2011-05-28 119 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