簡體   English   中英

JQuery ajax調用MVC操作總是在沒有錯誤時返回錯誤

[英]JQuery ajax call to MVC action always returns an error when there isn't one

這是一個MVC3應用程序。 我有以下javascript調用我的操作:

 function editDescription(docId,fileName, fileDescription) {
    $.ajax({
         type: "POST",
         url: "/OrderDetail/LoadModelData",
         contentType: "application/json; charset=utf-8",
         data: "{'id': '"+docId +"', 'filename': '"+fileName+"', 'description': '"+fileDescription+"'}",
         dataType: "json",
         success: function (result) {
         alert("ok: "+ result.d);
         },
         error: function (result) {
             alert('Oh no: '+ result.responseText);
         }
     });

繼承人我的行動:

    [HttpPost]
    public string LoadModelData(string id, string filename, string description)
    {
        return filename;
    }

我運行代碼,使用參數調用操作,沒有任何內容為null,但每次調用錯誤函數。 因此每次都會出現帶有“Oh no”的警告框,但是從動作返回的字符串是正確的。 如果文件名是test.pdf,則錯誤警告框會顯示

    'Oh No: test.pdf'. 

我看着Firebug並沒有錯誤。 盡管沒有錯誤,為什么不調用成功函數?

您期望(返回)操作方法中的string值。 為什么需要將數據類型指定為json呢? 刪除它,看看會發生什么。 響應中沒有d屬性! 所以只需在警報中使用結果。

$.ajax({
         type: "POST",
         url: "/OrderDetail/LoadModelData",
         contentType:"application/json; charset=utf-8",         
         data: JSON.stringify({ 
                             id: docId, 
                             filename: fileName, 
                             description: fileDescription 
                            }),
         success: function (result) {
         alert("ok: "+ result);
         },
         error: function (result) {
             alert('Oh no: '+ result.responseText);
         }
     });

datatype屬性告訴服務器客戶端期望返回哪種內容作為結果。

編輯:正如Darin所提到的,請使用JSON.stringify方法來構建JSON請求。 更新此答案以包含未來訪問者的正確方法。

永遠不要使用字符串操作構建JSON:

data: "{'id': '"+docId +"', 'filename': '"+fileName+"', 'description': '"+fileDescription+"'}",

絕對是可怕和錯誤的 你沒有編碼任何東西。 description只需引用一句話,一切都會破裂。 在操作JSON時始終使用JSON解析器

像這樣:

$.ajax({
     type: "POST",
     url: "/OrderDetail/LoadModelData",
     contentType: "application/json; charset=utf-8",
     data: JSON.stringify({ 
         id: docId, 
         filename: fileName, 
         description: fileDescription 
     }),
     success: function (result) {
         alert("ok: "+ result.filename);
     },
     error: function (result) {
         alert('Oh no: '+ result.responseText);
     }
 });

JSON.stringify方法是本機內置的現代瀏覽器。 如果您需要支持舊版瀏覽器,則可以包含json2.js腳本

另一個錯誤是你的控制器動作簽名。 在ASP.NET MVC控制器中,操作必須返回ActionResults,而不是字符串:

[HttpPost]
public ActionResult LoadModelData(string id, string filename, string description)
{
    return Json(new { filename = filename });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM