Jquery Ajax & WCF rest

Source: Internet
Author: 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)
{
// Code that runs when the application starts
    RegisterService();
}
void RegisterService()
{
    WebServiceHostFactory serviceHostFactory = new WebServiceHostFactory();
    RouteTable.Routes.Add(new ServiceRoute("Service", serviceHostFactory, typeof(Service)));
}
Service in typeof (Service): refers to the service class

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 = "Homepage" 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)
Method provided by this library: json2.js

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.