2010-08-16 77 views
13

我有以下代碼;

 $.ajax({ 
      url: "/Home/jQueryAddComment", 
      type: "POST", 
      dataType: "json", 
      data: json, 
      contentType: 'application/json; charset=utf-8', 
      success: function(data){ 
       //var message = data.Message; 
       alert(data); 
       $('.CommentSection').html(data); 
      } 

而在我的控制器;

[ValidateInput(false)] 
    public ActionResult jQueryAddComment(Comment comment) 
    { 
     CommentSection commentSection = new CommentSection(); 

     //ya da - ya da 
     // fill the commentsection object with data 

     //then 
     return PartialView("CommentSection", commentSection); 

    } 

但是,當我回到頁面時,成功警報不會發生。任何人都可以看到這個邏輯中的缺陷嗎?

+0

當前對帖子的回覆是什麼?用Firebug和/或Fiddler檢查響應。 – jfar 2010-08-16 01:58:29

+0

好點@jfar – griegs 2010-08-16 02:01:16

回答

25

您的期望JSON.Ajax POST中,但在ActionMethod中您返回了PartialView

嘗試:

$.ajax({ 
    url: "/Home/jQueryAddComment", 
    type: "POST", 
    dataType: "html", 
    data: json, 
    success: function(data){ 
     //var message = data.Message; 
     alert(data); 
     $('.CommentSection').html(data); 
    } 
} 
+0

這是一個很好的觀點。我返回一個json對象,但然後data.message爲空 – griegs 2010-08-16 02:02:09

+0

是啊看起來像你可能只是返回HTML和Javascript期待一個'JSON對象'... – xandercoded 2010-08-16 02:04:59

+0

如果我返回JSON,然後警告這個window.alert(數據)我得到對象。那麼現在我該如何在對象中獲取html。 – griegs 2010-08-16 02:12:59

0

除非它被複制錯誤它出現你缺少一些收令牌。

 $.ajax({ 
     url: "/Home/jQueryAddComment", 
     type: "POST", 
     dataType: "json", 
     data: json, 
     contentType: 'application/json; charset=utf-8', 
     success: function(data){ 
      //var message = data.Message; 
      alert(data); 
      $('.CommentSection').html(data); 
      } //<-- added close for anonymous function 
     }); //<--added close/semicolon for ajax function 

此外,您正在發佈,但它的行爲似乎沒有[Post]屬性。當你在調試器中運行這個命令時,你的操作中的斷點會被觸發嗎?

+0

對不起,關閉標記是正確的,我只是沒有複製整個功能 – griegs 2010-08-16 01:47:07

+1

PostAttribute是沒有必要的,它會接受所有HTTP動詞時不存在... – xandercoded 2010-08-16 01:50:13

+0

在jQueryAddComment上做斷點'在調試器中擊中? – jwsample 2010-08-16 01:50:19