1

我正在使用$.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那很好。我认为我将数据发送到服务器的方式存在一些问题。

我的客户端代码是:function 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....

    }
}
4

3 回答 3

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);
   }
});
于 2013-03-12T08:09:11.590 回答
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);
        }
    });
于 2013-03-12T08:15:38.473 回答
0

在我的调用中,我指定dataType: "json",并将整个data参数括在引号中。

例如

    $.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);
        }
    });
于 2013-03-12T08:11:24.837 回答