用jQuery调用WCF

1,服务

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

/// <summary>
/// Summary description for HelloService
/// </summary>
[ServiceContract]
[AspNetCompatibilityRequirements(
    RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class HelloService
{
    [OperationContract]
    public string Say(string word)
    {
        return string.Format("You say \"{0}\".", word);
    }

    [OperationContract]
    public string MSay(System.String word)
    {
        return string.Format("MM says that it is \"{0}\".",word);
    }

}

 

2,前台

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!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 type="text/javascript" src="javascript/jquery-1.4.1.min.js"></script>
        <script type="text/javascript">
            function submit_word() {
                //$.ajaxSettings.url = "HelloService.svc/Say";
                $.ajaxSettings.url = "HelloService.svc/MSay";
                $.ajaxSettings.type = "post";
                $.ajaxSettings.dataType = "json";
                $.ajaxSettings.contentType = "application/json";
                //WebService中这样写:"application/json; charset=utf-8"
                $.ajaxSettings.data = '{"word":"Hello, world"}';
                //WebService中这样写:'{word:"Hello, world"}'
                $.ajaxSettings.success = function (data) {
                    alert(data.d);
                };
                $.ajax();
            }   
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" value="提交" onclick="submit_word()"/>
    </div>
    </form>
</body>
</html>

 

3,配置

<?xml version="1.0"?>

<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
 
  <system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true">
      <serviceActivations>
        <add relativeAddress="HelloService.svc" service="HelloService" factory="System.ServiceModel.Activation.WebScriptServiceHostFactory"/>
      </serviceActivations>
    </serviceHostingEnvironment>
  </system.serviceModel>
 
</configuration>

 

你可能感兴趣的:(jquery)