2010-08-26 48 views
0

ASPX網站:MVC2:Ajax調用總是運行在錯誤函數中。爲什麼?怎麼了?

<script type="text/javascript"> 
function AjaxTest() { 

    var codeVal = "hello world"; 

    if (codeVal) { 
    $.ajax({ 
      type: "POST", 
      url: "CheckAge",  
      data: { code: codeVal }, 
      contentType: "application/json; charset=utf-8", 
      dataType: "json", 
      async: true, 
      cache: false, 
      success: function (result) { 
         alert("in ajax success"); 
      }, 
      error: function() { 
         alert("error"); 
      } 

      }); 
    } 
} 

它的雙重檢查,該JavaScript函數被調用。

控制器:

[HttpPost] 
public JsonResult CheckAge(String code) 
{ 
     return Json("abc"); 
} 

它結束了一直在阿賈克斯 - 錯誤 - 功能。不管怎樣,控制器功能都不會被調用。爲什麼? 爲什麼我總是出錯? 有什麼不對?

+0

我不認爲你可以指定動作,我想你也必須指定控制器。網址:「{Controller}/{Action}」;試試看。我也認爲你的[HttpPost]需要是[AcceptVerbs(HttpVerbs.Post)]。 – XstreamINsanity 2010-08-26 15:06:12

+0

thx 4你的評論。在所有的combian中測試了「MyController/Index」和[AcceptVerbs(HttpVerbs.Post)] - 沒有工作/解決我的問題。 :-(**注意:** [AcceptVerbs(HttpVerbs.Post)]是MVC風格,相當於MVC2中的[HttpPost](兩個)。 – user415876 2010-08-28 09:30:18

回答

2

檢查您發佈的網址。看起來你錯過了控制器部分。例如。它應該是/{controller}/{action}

如果該腳本是直接在視圖中(即不在外部JavaScript文件),你可以有這樣的:

$.ajax({ 
    type: "POST", 
    url: <%= Url.Action("CheckAge", "ControllerName") %>,  
    data: { code: codeVal }, 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    async: true, 
    cache: false, 
    success: function (result) { 
     alert("in ajax success"); 
    }, 
    error: function() { 
     alert("error"); 
    } 
}); 

而且,我覺得最好使用螢火蟲調試AJAX的東西。您可以在JavaScript中設置斷點並查看所有請求和響應。

HTHS,
查爾斯

編輯:儘量簡化的東西...例如

$.post('<%= Url.Action("CheckAge", "ControllerName") %>', 
     { code: codeVal }, 
     function (data) { 
      alert("in ajax success"); 
     }, 
     "json"); 
+0

Thx 4非常快速的幫助!是的,腳本直接在視圖中。結果:沒有更多的錯誤 - 但也沒有其他反應!!控制器函數「public JsonResult CheckAge(String code)」也不被調用。我是否需要一個「special」AJAX-Version;我使用了這樣可以嗎? – user415876 2010-08-26 19:01:17

+0

**正如上圖所示, 「ControllerName」到您的控制器名稱......對嗎?您是否使用過螢火蟲來查看發生了什麼?抱歉,沒有關注您的「特殊」AJAX版本......也不確定整個「腳本/ Ajax_0911/Start.js' javascript文件是。 – Charlino 2010-08-26 19:33:45

+0

** Excatly **當然意味着我用我的控制器的名稱替換了「ControllerName」,將兩個單引號放在「<%= ... %>「,並將」<%=「更改爲」<%:「;-)不,明天會設置firebug(它已經在這裏遲了;-)」Ajax Version「應該表示:在代碼中的某個地方,您會發現/ worte something像** **,或者?但是,你興奮地使用/寫了什麼? **「MicrosoftMvcAjax.js」**或**「MicrosoftAjax.js」**或??? – user415876 2010-08-26 19:48:31

相關問題