jQuery Ajax & WCF Rest

來源:互聯網
上載者:User

http://www.cnblogs.com/tyb1222/archive/2011/11/25/2263750.html

http://www.cnblogs.com/dudu/archive/2011/01/19/1939094.html

 

Global.asax.cs

 


using System.Web.Routing;
using System.ServiceModel.Activation;
void Application_Start(object sender, EventArgs e)
{
    // 在應用程式啟動時啟動並執行代碼
    RegisterService();
}
void RegisterService()
{
    WebServiceHostFactory serviceHostFactory = new WebServiceHostFactory();
    RouteTable.Routes.Add(new ServiceRoute("Service", serviceHostFactory, typeof(Service)));
}
typeof(Service)中的Service:指的是服務的類

Web.Config

<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
      <serviceActivations>
        <add relativeAddress="Service.svc" service="jQueryAjaxWcfRest.Service" factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>
      </serviceActivations>
    </serviceHostingEnvironment>
</system.serviceModel>

 

Service.cs

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

namespace jQueryAjaxWcfRest
{
    [ServiceContract]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class Service
    {
        [WebGet(UriTemplate = "/{id}"
            , ResponseFormat = WebMessageFormat.Json
            , RequestFormat = WebMessageFormat.Json)]
        public Person GetPerson(string id)
        {
            return new Person
            {
                Id = int.Parse(id),
                Age = 27,
                Name = "ZhangSan",
                Phone = "13090933221"
            };
        }

        [WebInvoke(UriTemplate = "/Post"
            , BodyStyle = WebMessageBodyStyle.WrappedRequest
            , ResponseFormat = WebMessageFormat.Json
            , RequestFormat = WebMessageFormat.Json)]
        public Person UpdatePerson(Person person)
        {
            return person;
        }

        [WebInvoke(UriTemplate="/Rest/Post"
            ,BodyStyle=WebMessageBodyStyle.WrappedRequest
            ,ResponseFormat=WebMessageFormat.Json
            ,RequestFormat=WebMessageFormat.Json)]
        public string Update(string message)
        {
            return string.Concat("hello", message);
        }

    }
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string Phone { get; set; }
    }
}

 

Default.aspx

<%@ Page Title="首頁" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="jQueryAjaxWcfRest._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/json2.js" type="text/javascript"></script>
    <script type="text/javascript">
        function showPerson() {

            $.ajax({
                type: "get",
                url: "Service/36",
                contentType: "application/json",
                success: function (json) {
                    $('#Id').val(json.Id);
                    $('#Name').val(json.Name);
                    $('#Age').val(json.Age);
                    $('#Phone').val(json.Phone);
                },
                error: function (error) {
                    $('#showerror').html(error.responseText);
                }
            });

//            var jsonData = { 'person': { 'Id': '36', 'Name': 'LiSi', 'Age': '24', 'Phone': '3232323'} };
//            var message = JSON.stringify(jsonData);
//            $.ajax({
//                type: 'post',
//                url: 'Service/Post',
//                contentType: 'application/json',
//                data: message,
//                dataType: 'json',
//                success: function (json) {
//                    $('#Id').val(json.Id);
//                    $('#Name').val(json.Name);
//                    $('#Age').val(json.Age);
//                    $('#Phone').val(json.Phone);
//                },
//                error: function (error) {
//                    $('#showerror').html(error.responseText);
//                }
//            });

//            var jsonMsg = { 'message': 'zhangsan' };
//            var message = JSON.stringify(jsonMsg);
//            $.ajax({
//                type: 'post',
//                url: 'Service/Rest/Post',
//                contentType: 'application/json',
//                data: message,
//                dataType: 'text',
//                //processData: false,
//                success: function (json) { alert(json) },
//                error: function (error) { alert(error.responseText); }
//            });

        }
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <input id="msg" type="text" name="name" value=" " />
    <input type="button" value="showperson" onclick="showPerson()" />
    <input type="text" id="Id" />
    <input type="text" id="Name" />
    <input type="text" id="Age" />
    <input type="text" id="Phone" />
    <div id="showerror">
    </div>
</asp:Content>

JSON.stringify(jsonData)
需要用這個庫提供的方法:json2.js
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.