Asp.net

ASP.NET:jQuery AJAX ‘data’ 參數問題

  • July 10, 2012

我在過去 3 個小時裡一直在研究這段程式碼並試圖找到答案。由於我沒有成功,我將只發布程式碼並詢問我應該在我的 Web 服務上使用哪種參數來處理此請求:

var args = [{ key: 'myId', value: 'myValue' }, { key: 'myOtherId', value: 'myOtherValue'}];
var dataToSend = { name: 'fooId', value: 'fooValue', args: args };
$.ajax({
type: 'POST',
url: 'fooURL',
data: dataToSend,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: OnSuccess,
error: OnError
});

現在,我應該需要哪種簽名才能獲得我的“dataToSend”?

我試過了:

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name, object value, List<Args> args)
{
   return "OK";
}

public class Args
{
   public string key { get; set; }
   public object value { get; set; }
}

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name, object value, object[] args)
{
   return "OK";
}

並且

[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(dataToSend dataToSend)
{
   return "OK";
}

public class dataToSend
{
   public string name { get; set; }
   public object value { get; set; }
   public List<Args> args = new List<Args>();

}
public class Args
{
   public string key { get; set; }
   public object value { get; set; }
}

嘗試將數據作為字元串而不是對像傳遞,即:

$.ajax({
...
數據:'{a:2,b:3}',
...
} );

這樣做的原因是,如果您將對象指定為數據,那麼 jQuery 使用查詢字元串格式序列化數據,而伺服器直接期望 JSON 格式。

儘管告訴 jQuery 使用 JSON 作為數據類型,但還是會發生這種情況——它似乎只與結果有關,與發送到伺服器的請求負載無關。

你在那裡的所有其他東西對我來說都是正確的。

雖然這是一篇較舊的文章,但我認為我會做出貢獻。我一直在發送一個關聯數組與我接受的文章相同的想法,我只是覺得它更容易寫。

Javascript

postData[0] = 'data!';
postData[1] = 'moar data!';
postData[2] = 'and some data';

$.ajax({
   type: 'POST',
   url: 'postUrl',
   data: { data: postData },
});

PHP

$data = $_POST['data'][0];
$moar_data = $_POST['data'][1];
$and_some_data = $_POST['data'][2];

引用自:https://stackoverflow.com/questions/1061884