我有一个如下所示的对象:
{
"json": [{
"Contract": "....",
"SupervisorID": "..."
},{
"Contract": "...",
"SupervisorID": "..."
}]
}
上面的对象是这样构建的。我得到所选的复选框,并将它们的ID添加到对象数组中。
var jsonArr = [];
var sps = $('#measuresUnApprovedModal').find('[name="chkbox_op"] input[type="checkbox"]:checked');
sps.each(function (i) {
var id = $(this).attr("id");
var idParts = id.split("_");
jsonArr.push({
"Contract": idParts[1],
"SupervisorID" : idParts[2]
});
});
如何在服务器端获取这些值?我目前的尝试看起来像这样:
$.ajax({
type: "POST",
url: "[REMOVED]",
data: { json: jsonArr },
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (msg) {
if (msg.d) {
alert("Success");
}
else { alert("Error has occured."); }
}).fail(function () {
alert("An unexpected error has occurred during processing.");
});
Web服务:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SendEmail(List<SupervisorToEmail> json)
{
return "Hi";
}
}
public class SupervisorToEmail
{
public string Contract { get; set; }
public string SupervisorID { get; set; }
}
public class Supervisors
{
private List<SupervisorToEmail> SupervisorsToEmail { get; set; }
}
答案 0 :(得分:1)
我认为问题出在你的ajax请求中,你需要为数据参数传递jQuery一个JSON字符串,而不是JavaScript对象,这样jQuery就不会尝试对你的数据进行URLEncode。
这应该有效:
$.ajax({
url: "[REMOVED]",
type: "POST",
data: JSON.stringify({ json: jsonArr }),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (msg) {
if (msg.d) {
alert("Success");
}
else {
alert("Error has occured.");
}
}).fail(function () {
alert("An unexpected error has occurred during processing.");
});
&#13;
答案 1 :(得分:0)
不确定我做了什么,但以下是结果代码:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SendEmail(List<SupervisorToEmail> Supervisors)
{
foreach (SupervisorToEmail supervisor in Supervisors)
{
}
return null;
}
public class SupervisorToEmail
{
public string Contract { get; set; }
public string SupervisorID { get; set; }
}
和Jquery:
$('#btnSendUnApprovedEmail').click(function () {
var jsonArr = new Array();
var sps = $('#measuresUnApprovedModal').find('[name="chkbox_op"] input[type="checkbox"]:checked');
sps.each(function (i) {
var id = $(this).attr("id");
var idParts = id.split("_");
var obj = new Object();
obj.Contract = idParts[1];
obj.SupervisorID = idParts[2];
jsonArr.push(obj);
});
var data = JSON.stringify(jsonArr);
alert(data);
$.ajax({
type: "POST",
url: "DailyMeasuresServiceHandler.asmx/SendEmail",
data: JSON.stringify({ Supervisors : jsonArr}),
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (msg) {
if (msg.d) {
alert("Success");
}
else { alert("Error has occured."); }
}).fail(function () {
alert("An unexpected error has occurred during processing.");
});
});