sbje098 2017-07-10 10:51 采纳率: 0%
浏览 1491

关于Ajax Post Json数据到Webservice

客户端代码:
function LoadData4() {
$.ajax({
type: "POST",
url: "http://localhost:6698/WebServiceTestJson2.asmx/TestJson2",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: "{'students': [{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]}",
success: function (json) { alert(json.d) },
error: function (error) {
alert("调用出错" + error.responseText);
}
});
}
Webservice代码:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string TestJson2(string students)
{
WriteLog(students);
try
{
if (students == null || students == "")
return "No data";
JavaScriptSerializer js = new JavaScriptSerializer();
List list = js.Deserialize>(students);
string test = "";
string other = "";
for (int i = 0; i < list.Count; i++)
{
test = test + list[i].Name;
other = other + list[i].other.other1;
}
return test + "\" + other;
}
catch (Exception e)
{
return e.ToString();
}
}

    public class Student
    {
        public string Name { get; set; }
        public string Sex { get; set; }
        public string Age { get; set; }
        public string Address { get; set; }
        public Other other { get; set; }

    }

             public class Other
    {
        public string other1 { get; set; }
        public string other2 { get; set; }
    }

当我在客户端调用的时候报错:
Type \u0027System.String\u0027 is not supported for deserialization of an array!

但是我在Webservce上直接用下面的Json字符串用Invoke调用是没有任何问题。
[{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]

请教各位大神,是什么原因导致客户端调用出错?谢谢!

  • 写回答

3条回答 默认 最新

  • Go 旅城通票 2017-07-11 01:50
    关注

    自己比较2个字符不就知道了,ajax传递的是JSON对象,不是JSON对象数组,你要序列化的为对象数组,肯定不行了

    data: "{'students': [{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]}",

    ===>去掉{'students': 和最后的},传递json对象数组,而不是json对象

    data: "[{'name':'John','sex':'man','age':'25','other':{'other1':'msgother1','other2':'msgother2'}},{'name':'Tom','sex':'man','age':'21','address':'Hangzhou','other':{'other1':'msgother3','other2':'msgother4'}}]",

    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献