我已经在HTML,JS和AJAX中创建了一些代码,但它并不像我想要的那样。
<script type="text/javascript">
function DeleteSelectedRecord(id) {
alert(id);
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: '{"id":"' + id + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});
}
function CreateATableFromDataBase() {
var deserializedData = '<%=serializedList %>';
deserializedData = JSON.parse(deserializedData);
for (var i = 0; i < deserializedData.length; i++) {
document.write(
"<tr>" +
"<th scope=\"row\">" + i.toString() + "</th>" +
"<th>" + deserializedData[i]["Name"] + "</th>" +
"<th>" + deserializedData[i]["Where"] + "</th>" +
"<th>" + deserializedData[i]["Destination"] + "</th>" +
"<th><input type=\"button\" class=\"btn btn-primary\" onclick=\"DeleteSelectedRecord(" + deserializedData[i]["Id"] + ")\" value=\"Delete\"/></th>" +
"</tr>"
);
}
}
</script>
第二个函数将参数“id”传递给第一个参数。我已经使用了警报方法来检查,至少它是否正常工作。确实如此。当我想将参数传递给PrintTasks.aspx.cs文件中名为DeleteRecord的超级方法时,问题就开始了......
[System.Web.Services.WebMethod]
public static void DeleteRecord(int id)
{
very sophisticated code...
}
内心并不重要。最奇怪的是它没有读取我的参数。
谢谢!
答案 0 :(得分:0)
只需更改此行代码即可。它会起作用
data: '{"id":"' + id + '"}',
更改为
data: { id:id},
第一个id是您在.cs文件方法中设置的参数名称..和第二个 一个是你要传递的价值......
答案 1 :(得分:0)
尝试如下所述:
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord?id=" + id,
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});
或
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: JSON.stringify({id:id}),
contentType: "application/json;",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});
答案 2 :(得分:0)
使用$ .param()函数将数据发送到服务器。 这是代码:
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: $.param({"id": id}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});
答案 3 :(得分:-1)
Try by changing your ajax code
$.ajax({
type: "POST",
url: "PrintTasks.aspx/DeleteRecord",
data: '{"id":"' + ParseInt(id) + '"}',//change your code here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
alert("Deleted!");
},
failure: function () {
alert("Failure!");
}
});