我正在使用$.ajax
向Asp.Net中的C#代码发送请求。每次我收到响应中的错误(在Firebug中检查),如:
{"Message":"Invalid JSON primitive: EmailAddress.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
如果我从data:{}
删除了$.ajax
参数,那就没关系了。我认为我向服务器发送数据的方式存在问题。
我的客户端代码是: 函数send_req(){
$.ajax({
url: "Demo.aspx/Demo_Method",
contentType: "application/json; charset=UTF-8",
type: "POST",
data: {"EmailAddress": "abc@testmail.com"},
success: function (response) {
alert('Success' + response);
}
});
}
Demo.aspx.cs页面代码是:
public partial class Demo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod()]
public static void Demo_Method(string EmailAddress)
{
//Some code....
}
}
答案 0 :(得分:2)
删除EmailAddress
参数附近的引号:
$.ajax({
url: "Demo.aspx/Demo_Method",
contentType: "application/json; charset=UTF-8",
type: "POST",
data: {EmailAddress: "abc@testmail.com"},
^^^^^^^^^^^^
success: function (response) {
alert('Success' + response);
}
});
答案 1 :(得分:0)
在我的调用中,我指定dataType: "json"
,并将整个data
参数包装在引号中。
e.g。
$.ajax({
url: "Demo.aspx/Demo_Method",
contentType: "application/json; charset=UTF-8",
type: "POST",
dataType: "json",
data: "{'EmailAddress':'abc@testmail.com'}",
success: function (response) {
alert('Success' + response);
}
});
答案 2 :(得分:0)
尝试将数据作为字符串传递,而不是作为对象。
示例:
$.ajax({
url: "Demo.aspx/Demo_Method",
contentType: "application/json; charset=UTF-8",
type: "POST",
data: '{"EmailAddress": "abc@testmail.com"}',
success: function (response) {
alert('Success' + response);
}
});