2013-10-28 188 views
0

我想發送一個列表作爲參數與AJAX但在我的函數參數爲空。我可以用json解決這個問題,但IE 7不支持json.this是我的代碼。我該如何解決這個問題?發送列表作爲參數與AJAX

$(function() { 
    $('#DeleteUser').click(function() { 
     var list = []; 
     $('#userForm input:checked').each(function() { 
      list.push(this.id); 
     }); 
     $.ajax({ 
      url: '@Url.Action("DeleteUser", "UserManagement")', 
      data: { 
       userId: list 
      }, 
      type: 'POST', 
      success: function (result) { 
       alert("success"); 
      }, 
      error: function (result) { 
       alert("error!"); 
      } 
     }); //end ajax 
    }); 
}); 
+0

你可以嘗試2個事情(以前有過這種情況),給你的ajax調用,添加「datatype:'application/json'」和/或「tradional:true」。希望它可以工作 – Jose

+0

這是一個cshtml文件嗎? –

回答

0

添加道格拉斯Crockford的著名json2.js,以及使用功能檢測,從文檔填充工具JSON序列化的兼容性

https://github.com/douglascrockford/JSON-js

JSON.stringify(value, replacer, space) 
value  any JavaScript value, usually an object or array. 

replacer an optional parameter that determines how object 
      values are stringified for objects. It can be a 
      function or an array of strings. 

space  an optional parameter that specifies the indentation 
      of nested structures. If it is omitted, the text will 
      be packed without extra whitespace. If it is a number, 
      it will specify the number of spaces to indent at each 
      level. If it is a string (such as '\t' or ' '), 
      it contains the characters used to indent at each level. 

提出更改代碼:

{ ... data: JSON.stringify(list) ... } 
+0

我只是將json2.js添加到我的頁面並更改數據,因爲您說它仍將空發送給我的列表 –

0

可能有幾個原因會導致失敗

從代碼中可以看出您使用剃鬚刀。如果這不是在剃刀視圖(即一個.cshtml文件)您的鏈接將不正確。

如果鏈接是正確的,那麼代碼將工作,假設您的控制器設置正確。由於數據不會成爲URL的一部分,因此您需要爲userId參數指定FromBody

public ActionResult DeleteUser([FromBody] userId){ 
    //implementation 
} 

或者,你可以在列表中添加到URL

url: '@Url.Action("DeleteUser", "UserManagement")/' + list 

當然和在Global.asax的路由發送的第一個參數的用戶ID

+0

它不起作用。 –

+0

如果您希望獲得更多幫助,則需要提供更多信息。這個概念確實起作用,所以只有你知道 –

+0

以上的所有內容都不起作用,只有你知道,除了「當然有一個路徑在global.asax中發送第一個參數給userId」(我不知道你在說什麼意味着??)在我的行動參數是null如前 –