AJAX 調用WebService 、WebApi 增刪改查(筆記)


 經過大半天努力,終於完成增刪改查了!心情有點小激動!!對於初學者的我來說,一路上都是迷茫,坑!!雖說網上有資料,可動手起來卻不易(初學者的我)。(苦逼啊!)

 

WebService 頁面:

/// <summary>
    /// TsetWeb 的摘要說明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調用此 Web 服務,請取消注釋以下行。 
    [System.Web.Script.Services.ScriptService]
    public class TsetWeb : System.Web.Services.WebService
    {
        TestBll bll = new TestBll();

        [WebMethod(Description = "獲取所有對象信息")]
        public string AllUserJson()
        {
            return ToJson(bll.GetAllUser());
        }

        [WebMethod(Description = "添加一個對象信息")]
        public string SetUserJson(string name ,string phone)
        {
            return ToJson(bll.SetAddUser(name,phone));
        }
        [WebMethod(Description = "刪除一個對象信息")]
        public string DelUserJson(int id)
        {
            return ToJson(bll.DelUser(id));
        }
        [WebMethod(Description = "更改一個對象信息")]
        public string Update(int id, string name, string phone)
        {
            Test user = new Test();
            user.id = id;
            user.name = name;
            user.phone = phone;
            return ToJson(bll.Update(user));
        }

        //對數據序列化,返回JSON格式 
        public string ToJson(object obj)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            return serializer.Serialize(obj);
        }
    }

  AJAX調用WebService 頁面:

<body>
    <form id="form1" runat="server">
    <div>
        <table id="tab">
            <tr>
                <td>編號</td>
                <td>名字</td>
                <td>電話</td>
                <th>操作</th>
            </tr>
        </table>
    </div>
        <input type="button" name="add" id="add" value="添加" />
    </form>
    <script src="Scripts/jquery-1.7.1.min.js"></script>
    <script>
        $(function() {
            $.ajax({
                url: "/TsetWeb.asmx/AllUserJson",
                contentType: 'application/json',
                dataType: "json",
                type: "post",
                success: function(data) {
                    var a = eval("(" + data.d + ")"); //后台返回是字符串,所以轉換為json對象
                    $.each(a, function(index, item) {
                        var tr = $("<tr/>");
                        $("<td/>").html(item["id"]).appendTo(tr);
                        $("<td/>").html(item["name"]).appendTo(tr);
                        $("<td/>").html(item["phone"]).appendTo(tr);
                        $("<button id ='d' onclick='del(" + item["id"] + ")'>").html("刪除").appendTo(tr);
                        $("<button id ='u' onclick='updata(" + item["id"] + ")'>").html("更新").appendTo(tr);
                        tr.appendTo("#tab");
                    });
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
                }
            });
        });
        $("#add").click(function() {
            $.ajax({
                url: "/TsetWeb.asmx/SetUserJson",
                data: "{name:'李六',phone:'13727713819'}",
                contentType: 'application/json',
                dataType: "json",
                type: "post",
                success: function (data) {
                    var a = eval("(" + data.d + ")"); //后台返回是字符串,所以轉換為json對象
                    alert(a);//返回1表示成功
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
                }
            });
        });
        function del(id) {
            $.ajax({
                url: "/TsetWeb.asmx/DelUserJson",
                type: "Post",
                data: { "id": id },
                dataType: "json",
                success: function (data) {
                    var a = eval("(" + data.d + ")"); //后台返回是字符串,所以轉換為json對象
                    alert(a);//返回1表示成功
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
                }
            });
        }

        function updata(id) {
            $.ajax({
                url: "/TsetWeb.asmx/Update",
                type: "Post",
                data: { "id": id, "name": '九九', "phone": '15927713819' },
                dataType: "json",
                success: function (data) {
                    var a = eval("(" + data.d + ")"); //后台返回是字符串,所以轉換為json對象
                    alert(a);//返回1表示成功
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
                }
            });
        }
    </script>
</body>

  AJAX調用WebService結果:

 

WebApi頁面:

public class ValuesController : ApiController
    {
        TestBll bll = new TestBll();

        // GET api/values/GetAll()
        [HttpGet]
        public List<Test> GetAll()
        {
            return bll.GetAllUser();
        }
        [HttpPost]
        public int PostNew([FromBody]Test user)
        {
            return bll.SetAddUser(user.name, user.phone);
        }
        [HttpPost]
        public int PostNew(string name ,string phone)
        {
            return bll.SetAddUser(name, phone);
        }

        [HttpDelete]
        public int Delete([FromBody]Test user)
        {
            return bll.DelUser(user.id);
        }

        [HttpPut]
        public int Put([FromBody] Test user)
        {
            return bll.Update(user);
        }
    }

  AJAX調用WebApi頁面:

<div>
    <table id="tab">
        <tr>
            <th>編號</th>
            <th>名字</th>
            <th>電話</th>
            <th>操作</th>
        </tr>
    </table>
    <input type="button" name="add" id="add" value="添加" />
</div>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
 <script>
     $(function() {
         $.ajax({
             url: "api/Values/GetAll",
             type: "GET",
             dataType: "json",
             success: function(data) {
                 $.each(data, function(index, item) {
                     var tr = $("<tr/>");
                     $("<td/>").html(item["id"]).appendTo(tr);
                     $("<td/>").html(item["name"]).appendTo(tr);
                     $("<td/>").html(item["phone"]).appendTo(tr);
                     $("<button id ='d' onclick='del(" + item["id"] + ")'>").html("刪除").appendTo(tr);
                     $("<button id ='u' onclick='updata(" + item["id"] + ")'>").html("更新").appendTo(tr);
                     tr.appendTo("#tab");
                 });
             },
             error: function(XMLHttpRequest, textStatus, errorThrown) {
                 alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
             }
         });
         
     });
     $("#add").click(function () {
         $.ajax({
             url: "api/Values/Put",
             type: "Put",
             data: {"id":id, "name":'趙七',"phone":'15727713819'},
             dataType: "json",
             success: function (data) {
                 alert(data);//返回1表示成功
             },
             error: function (XMLHttpRequest, textStatus, errorThrown) {
                 alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
             }
         });
     });
     function del(id) {
         $.ajax({
             url: "api/Values/Delete",
             type: "Delete",
             data: { "id": id },
             dataType: "json",
             success: function (data) {
                 alert(data);//返回1表示成功
             },
             error: function (XMLHttpRequest, textStatus, errorThrown) {
                 alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
             }
         });
     }

     function updata(id) {
         $.ajax({
             url: "api/Values/Put",
             type: "Put",
             data: { "id": id, "name": '黃八', "phone": '15927713819' },
             dataType: "json",
             success: function (data) {
                 alert(data);//返回1表示成功
             },
             error: function (XMLHttpRequest, textStatus, errorThrown) {
                 alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
             }
         });
     }
    </script>

  AJAX調用WebApi結果:

PS:雖然一路上的坑,回想起來也不錯,這過程!!欠缺太多了!!(第一次筆記。)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM