有人可以解释一下为什么这会给我一个错误吗?
我的ajax调用是这样的。
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(document).ready(function () {
$('#btn1').click(function () {
var values = JSON.stringify({ data: $('#form1').serializeArray() });
alert($('#form1').serializeArray());
$.ajax({
type: "POST",
url: "Default.aspx/Test",
contentType: "application/json; charset=utf-8",
scripts: true,
dataType: "json",
data: values,
success: function (data) { $('#results').append(data.d); },
error: function () { $('#results').append('hata'); }
});
}); });
</script>
</head>
<body>
<form runat="server" id="form1">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
<button id="btn1" type="button">bummm</button>
<div id="results"></div>
</form>
</body>
</html>
[WebMethod]
public static string Test (string data)
{
return "İşlem başarılı"+data;
}
它说我{“Message”:“类型\u0027System.String\u0027 不支持数组的反序列化。”,“StackTrace”:“
最佳答案
我认为发生这种情况是因为你错误地使用ajax调用了你的web方法。
您的 webmethod 有一个名为 data
的参数类型 string
,但您尝试不带名称发送,因此请尝试更改您的代码,如下所示:
var KaydetDataWithAjax = function (e)
{
var values =JSON.stringify({data: $(e).serializeArray()});
alert(values);
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "Harita.aspx/HaritaKaydet",
scripts: true,
data:values,
success: function (dt) { alert(dt);},
complete:function(){},
error: function () { alert('error'); }
});
};
更新
此方法适用于新项目
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "Harita.aspx/HaritaKaydet",
scripts: true,
data:JSON.stringify({data: 'text'}),
success: function (dt) { alert(dt);},
complete:function(){},
error: function () { alert('error'); }
});
如果在您的情况下它不起作用,那么如果您提供更多代码可能会有所帮助
更新2
事实证明这一切比我想象的简单!
serializeArray()
返回数组!因此它在服务器方法上找到类似 List<object>
的参数,所以要解决这个问题,你也必须对数组进行字符串化
所以试试这个代码
var KaydetDataWithAjax = function (e)
{
var values =JSON.stringify({data: JSON.stringify($(e).serializeArray())});
alert(values);
$.ajax({
type: "POST",
dataType: 'json',
contentType: "application/json; charset=utf-8",
url: "Harita.aspx/HaritaKaydet",
scripts: true,
data:values,
success: function (dt) { alert(dt);},
complete:function(){},
error: function () { alert('error'); }
});
};
关于asp.net - 使用 Web 方法进行 Ajax 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20000741/