一、下载json2.js

二、客户端代码:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script language="javascript" src="JS/jquery-1.3.2.js" type="text/javascript"></script>
    <script src="JS/json2.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        $(document).ready(function() {
           $('#Button3').click(function() {
                SaveStu();
            });
        });
        //保存功能
        function SaveStu() {

    //创建一个json对象
            var student = { "StuNo": $('#no').val(), "Name": $('#name').val(), "Sex": $('#sex').val(), "Score": $('#score').val(), "Age": $('#age').val() };
            var param = new Object();
            param.student = student;//param.student中的student必需和webservice中对应方法的参数名一致
            $.ajax({               
                type: "POST",
                contentType: "application/json",
                url: "WebService.asmx/SaveStudent",
                data: JSON.stringify(param), //调用json2.js中的方法,这里做object到string的转换,如果这里不使用该方法,webservice将获取不到对象而出错
                dataType: 'json',
                success: function(data) {

        alert(data);
                },
                error: function() {
                    alert('错了!');
                }
            });
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

三、webservice中对应的方法

[WebMethod]
    public string SaveStudent(Student student)
    {

    return student.Name;
     }

四、student类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
///Student 的摘要说明
/// </summary>
public class Student
{
    public Student()
    {

    }
    public int StuNo { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public int Score { get; set; }
    public int Age { get; set; }
}

posted on 2011-05-10 17:36  aparche  阅读(667)  评论(0编辑  收藏  举报