JQuery调用WCF服务

一:创建一个wcf服务项目

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        string GetName(string name);

    }

服务可以使用WebHttpBinding以及WebGet或者WebInvoke属性来暴露。这些属性每一个都确定HTTP动作、消息格式以及需要暴露给一个操作的消息体形式

①WebGet属性使用GET动词暴露操作。GET相对于其他HTTP动作有重要的优势。首先,通过在一个浏览器地址栏中输入服务URI可以直接地访问终结点。参数可以作为查询字符串或者编码字符串在URI中发送。其次,客户端以及其他下游系统比如代理服务器可以很容易地基于缓存策略来为服务缓存资源。由于缓存能力,WebGet属性应该只用来做收集用

②WebInvoke属性被用于那些修改数据的添加或者删除客户信息的操作。最后,在WebGet和WebInvoke属性上定义UriTemplate属性来使用URI定义一个自定义资源

支持的参数残敌格式 Get类型:参数传递格式:{ "name": name }  Post类型:参数传递格式:'{"name":"'+name+'"}'  Post参数传递时必须写成string类型

④RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json

说明传递近来的数据都是JSON形式的,只有两种形式,一个是JSON,一个是XML.

⑤BodyStyle = WebMessageBodyStyle.WrappedRequest是把参数包装一下这样可以传递多个参数进来,

namespace JqueryWcfTest3
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    
// [JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")] 作用返回值是json格式的
public class Service1 : IService1 {
//Method 请求格式,当跨域请求时必须是GET类型 [WebInvoke(Method ="GET",RequestFormat
= WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)] public string GetName(string name) { return "北京市九好市民"+name; } } }

①AspNetCompatibilityRequirements属性确保端点使用了WEBHTTP绑定模型与webconfig中的

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />配合使用

 ②OperationContract属性把方法公开在WCF服务中

二、Web.config配置

<?xml version="1.0" encoding="utf-8"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>

    <services>
      <!--webHttpBinding 必须要有,否则程序请求有误 -->
      <service name="JqueryWcfTest3.Service1">
        <endpoint address="" binding="webHttpBinding" contract="JqueryWcfTest3.IService1" behaviorConfiguration="AllenBehavior"/>
      </service>
    </services>
    <behaviors>     
      <endpointBehaviors>
        <behavior name="AllenBehavior">
          <enableWebScript/> <!--JavaScript 访问,必须要有-->                  
        </behavior>
      </endpointBehaviors>
  
      <serviceBehaviors>
        <behavior>
          <!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- 这个必须要有,可以查看错误信息 -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    
    </behaviors>
  
    <serviceHostingEnvironment aspNetCompatibilityEnabled ="true">
      <!--serviceActivations  添加一个指定激活服务应用程序的配置元素, 这里要配置服务激活相关的选项:-->
      <serviceActivations>
        <!--  relativeAddress是相对地址,service是我们定义的服务的名字,记住这里不要把service设置为契约名字,否则会出现错误。-->
        <add relativeAddress="JqueryWcfTest3.Service1.svc" service="JqueryWcfTest3.Service1" factory="System.ServiceModel.Activation.WebScriptServiceHostFactory" />
      </serviceActivations>
    </serviceHostingEnvironment>


  </system.serviceModel>

</configuration>

三、本地请求Html页面

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="jquery-1.10.2.js"></script>
    <meta charset="utf-8" />
    <script>
        $(function() {
            $.ajax({
                type: "post",
                url: "/Service1.svc/GetName",
                dataType: 'text/json',
                contentType:"application/json",
                data:'{"name":"xiaoyao"}',
                success: function (data) {
                    console.log(data);
                },
                error: function (txt) {
                    console.log(txt);
                }
            });
        })
    </script>
</head>
<body>
</body>
</html>

结果

四、跨域请求

       $.ajax({
            type: "get",
            url: "http://localhost:49719/Service1.svc/GetName?name=xiaoyao",
            dataType: 'jsonp',
            jsonp: "callback",
            contentType: "application/json",            
            success: function (data) {
                console.log(data);
            },
            error: function (txt) {
                console.log(txt);
            }
        });

注释:

Jaxa可以进行跨域请,但仅限于GET请求方式,并且数据格式是jsonp形式的

JSONP是一个非官方的协议,它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实现形式)要点就是允许用户传递一个callback参数给服务端,然后服务端返回数据时会将这个callback参数作为函数名来包裹住JSON数据,这样客户端就可以随意定制自己的函数来自动处理返回数据了。

1、ajax和jsonp这两种技术在调用方式上“看起来”很像,目的也一样,都是请求一个url,然后把服务器返回的数据进行处理,因此jquery和ext等框架都把jsonp作为ajax的一种形式进行了封装;

2、但ajax和jsonp其实本质上是不同的东西。ajax的核心是通过XmlHttpRequest获取非本页内容,而jsonp的核心则是动态添加<script>标签来调用服务器提供的js脚本。

3、所以说,其实ajax与jsonp的区别不在于是否跨域,ajax通过服务端代理一样可以实现跨域,jsonp本身也不排斥同域的数据的获取。

4、还有就是,jsonp是一种方式或者说非强制性协议,如同ajax一样,它也不一定非要用json格式来传递数据,如果你愿意,字符串都行,只不过这样不利于用jsonp提供公开服务。

json与jsonp数据格式的区别

Json格式
{
    "method":"get",
    "result":"ok"
}

jsonp格式

callback({
    "method":"get",
    "result":"ok"
})

错误提示

①异常消息为“传入消息的消息格式不应为“Raw”。此操作的消息格式应为 'Xml', 'Json'

    在最后$.ajax中添加--contentType: "application/json",即可...

②415 Cannot process the message because the content type 'application/x-www-form-urlencoded' was not the expected type 'text/xml; charset=utf-8'"

   需要在Web.config中绑定webHttpBinding

遇到了无效消息正文。预期找到名为“type”、值为“object”的特性,但找到的值为“null”

   data:'{"name":"xiaoyao"}' data必须要传string类型,不能是字典以及实体

原文地址:https://www.cnblogs.com/xiaoyaodijun/p/6782272.html