【www.gdgbn.com--WebService】
本文章是利用jquery的ajax调用webservice返回json数组哦,json数据是网页特效的一种小型轻型数据,实时交互性更强于xml哦。
json数据
{"employee":[{"name":"john","sex":"man","age":"25"},{"name":"tom","sex":"man","age":"21"},{"name":"mary","sex":"woman","age":"21"}]}
//jquery 调用webservice导入数据
function loaddata() {
var studentdata = collectiondata();
$.ajax({
url: "importdataservice.asmx/importstu",
type: "post",
contenttype: "application/json;charset=utf-8",
datatype: "json",
data: "{"students":[{"name":"kobe ","sex":"boy","age":"20"},{"name":"mary","sex":"girl","age":"19"}]}",
success: function(result) {
alert(result.d);
},
error: function(e) {
alert(e.responsetext);
}
});
}///
///
///
///
///
[webmethod]
[scriptmethod(responseformat=responseformat.json)]
public string importstu(dictionary[]students)
{
if (students.length == 0)
{
return "没有任何数据!";
}
else
{
try
{
foreach (dictionarystu in students)
{
//构造一个新的student对象。
student student = new student();//为新构造的student对象属性赋值。
foreach (string key in stu.keys)
{
switch (key)
{
case "name":
student.name = stu[key];
break;
case "sex":
student.sex = stu[key];
break;
case "age":
int age;
if (int32.tryparse(stu[key], out age))
{
student.age = age;
}
else
{
student.age = 0;
}
break;
default:
break;
}
}
}
return "导入学生成功!";
}
catch
{
throw new exception("导入学生失败!");
}
}
}