在我的项目中,我想使用ajax来进行JS和ASP之间的通信。但是,我得到了 500 错误。
JS ajax 中的 JSON 字符串:
{lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]}
C#:
[WebMethod]
public static string GetCurrentTime(List<string> lists)
{
return "text string" ;
}
完整的 AJAX:
var dataJson = "{lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]}";
$.ajax({
type: "POST",
url: URL,
data: dataJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
console.log(response.d);
}
最佳答案
尝试使用JSON.stringify
如下所示,用一个对象代替 List<string>
,
var dataJson = {lists: [{'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a111', 'colour': 'red'}, {'ID': 'a95fed0d-c1e4-45e8-2cd2-e5d7f099a222', 'colour': 'green'}]};
$.ajax({
type: "POST",
url: URL,
data: JSON.stringify(dataJson),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
console.log(response.d);
}
C#
public class Data {
public string ID {get;set;}
public string colour {get;set;} // This can be renamed into Pascal case here and in the json
}
[WebMethod]
public static string GetCurrentTime(List<Data> lists)
{
return "text string" ;
}
关于javascript - 如何在ajax中构建字符串数组并将其传递给asp?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40414999/