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

关于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条回答

  • blueskysoar blueskysoar 4年前

    补充下:data后面填写的可以是 字符串 或对象 。(前面说错了)

    点赞 评论 复制链接分享
  • blueskysoar blueskysoar 4年前

    data后面的值:去掉花括号外面的双引号看看吧,这儿填写的应该是一个js对象,不是字符串。

    点赞 评论 复制链接分享
  • showbo GoCityPass新加坡曼谷通票 4年前

    自己比较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'}}]",

    点赞 评论 复制链接分享