2011-02-09 43 views
1

試圖顯示來自控制器的成功消息?jsonresult不回來?

[HttpPost] 
    public JsonResult SuccesMsg() 
    { 
     return Json(new { Success = true }); 
    } 

的jQuery:

 $("#but").click(function() { 
      $.ajax({ 
       url: "/Home/SuccesMsg", 
       type: 'POST', 
       data: "", 
       success: function (result) { 
        if (resultJson['Success'] == true) { 
         alert('success'); 
        } 

        else 
        { alert('no'); } 
       }, 
       error: function (err) { alert('error') } 
      }); 
     }); 
+0

你在firebug中看到的反應是什麼? – 2011-02-09 11:50:01

+0

'resultJson`是什麼?是否有任何警報顯示? – 2011-02-09 11:50:24

+0

沒有反應,我改變了resultJson結果 – 2011-02-09 12:46:10

回答

3

添加數據類型: 「JSON」到$阿賈克斯來電或使用簡寫:$ .getJSON

還要檢查您的控制器是否處理狀態爲http 200(OK)的響應返回。

對於調試,您可以添加complete:function(){alert('complete');}來查看請求是否完成。良好的Firefox調試工具(附加組件)有Live http標頭和Firebug。

2

我認爲ü需要在您的jquery.ajax如下規定:

數據類型: 'JSON'

$("#but").click(function() { 
      $.ajax({ 
       url: "/Home/SuccesMsg", 
       dataType: 'json', // change code 
       type: 'POST', 
       data: "", 
       success: function (result) { 
        if (result['Success'] == true) { 
         alert('success'); 
        } 

        else 
        { alert('no'); } 
       }, 
       error: function (err) { alert('error') } 
      }); 
     }); 
1

只是測試這一點,它應該工作。你想

if (result.Success) {....} 

,而不是

if (resultJson['Success'] == true) {..} 

所以整個例如

[HttpPost] 
    public JsonResult SuccesMsg() 
    { 
     return Json(
      new 
      { 
       Success = true 
      } 
     ); 
    } 

$.ajax({ 
    url: '/Home/SuccesMsg', 
    type: 'POST', 
    success: function (result) { 
     if (result.Success) { 
      alert('success'); 
     } else { 
      alert('no'); 
     } 
    }, 
    error: function() { 
     alert('error'); 
    } 
}); 

你還應該指定具體的數據類型,但不是必需的: http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests

0

在MVC2使用JsonRequestBehavior.DenyGet已經說過here

[HttpPost] 
    public JsonResult SuccesMsg() 
    { 
     return Json(new { Success = true }, JsonRequestBehavior.DenyGet); 
    }