无法将JSON数组发送到服务器

时间:2015-11-18 12:05:15

标签: jquery json ajax methods

我使用以下命令在$ .each()方法中创建一个Json数组

JsonData.push({ "refpracid": refPracID, "Spec":funcSpec(refPracID), "FTE": funcFTE(refPracID) });

此功能将数据发布到服务器



function PostDataToServer(Data, methodName) {
    var obj = JSON.stringify(Data);
    $.ajax({
        type: "POST",
        data: obj,
        url: "FTE_ASP.aspx/" + methodName,
        // data: JSON.stringify(obj),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result) {
            if (result.d == "null") {
                RedirectToLogin();
            } else {
                SetValues(result);
            }
        },
        error: function (result) {
            $('#loadingIndicator').hide();
            alert("PostDatToServer: " + result.responseText);
            //RedirectToErrorPage();
        }
    });




这是Stringify

之后生成的JSON
[{"refpracid":"2436","Spec":"ALLERGIST | EAR NOSE & THROAT","FTE":"56"}]

这是我的服务器端功能

public static string UpdateFte(string[] refpracid,string[] Spec,string[] FTE)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    SqlConnection con = new SqlConnection(sqlConnectionString);
    SqlCommand cmd = new SqlCommand();
    DataSet ds = new DataSet();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = "UpdateFTE";
    cmd.CommandTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["SqlCommandTimeOut"]);
    cmd.Parameters.Add("@refpracname", SqlDbType.VarChar).Value = "";
    cmd.Parameters.Add("@specname", SqlDbType.VarChar).Value = "";
    cmd.Parameters.Add("@fte", SqlDbType.VarChar).Value = "";
    cmd.Parameters.Add("@UserID", SqlDbType.Int).Value = SessionVariables.UserID;
    cmd.Connection = con;
    try
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(ds);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }
    GridData gd = GetGridData(ds);
    return serializer.Serialize(gd);
}

但是当我尝试向服务器发送数据时,服务器拒绝我的呼叫,并显示以下错误消息。我搜索并重新检查但我无法理解为什么它会抛出这个错误。

{"Message":"Type \u0027System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\u0027 is not supported for deserialization of an array.","StackTrace":"   at System.Web.Script.Serialization.ObjectConverter.ConvertListToObject(IList list, Type type, JavaScriptSerializer serializer, Boolean throwOnError, IList\u0026 convertedList)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeInternal(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\r\n   at System.Web.Script.Serialization.ObjectConverter.ConvertObjectToTypeMain(Object o, Type type, JavaScriptSerializer serializer, Boolean throwOnError, Object\u0026 convertedObject)\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.InvalidOperationException"}

有人可以指出出错的地方吗?请!

3 个答案:

答案 0 :(得分:0)

您不希望将变量数据转换为字符串。 如果数据是JSON格式,请删除以下行。

var obj = JSON.stringify(Data);

否则使用:

var obj = JSON.parse(Data);

答案 1 :(得分:0)

你的JSON应该是

{
"refpracid":["abc","xyz"],
"Spec":["abc","xyz"],
"FTE":["abc","xyz"],
}

答案 2 :(得分:0)

将这些行添加到您的ajax中:

processData: false,
contentType: false

此外,您可以在ajax中使用FormData。例如:

var refpracid = [];
//push something to refpracid

var spec = [];
//push something to spec

var fte = [];
//push something to fte

//create a formData
var formData = new FormData();

//append data
formData.append('refpracid', refpracid);
formData.append('Spec', spec);
formData.append('FTE', fte);

所以,ajax应该是:

$.ajax({
   type: "POST",
   url: "FTE_ASP.aspx/" + methodName,
   data: formData,
   processData: false,
   contentType: false,
   success: function (result) {
      if (result.d == "null") {
         RedirectToLogin();
      }
      else {
         SetValues(result);
      }
   },
   error: function (result) {
      $('#loadingIndicator').hide();
      alert("PostDatToServer: " + result.responseText);
      //RedirectToErrorPage();
   }
});

希望这能帮到你