JQuery中用Ajax的POST方式与WCF交互

服务协定代码:

在OperationContract中用RequestFormat=WebMessageFormat.Json指定请求数据格式为Json,用ResponseFormat=WebMessageFormat.Json指定返回格式为Json,用Method="POST"指定提交方式为POST。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCF_AjaxService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IAjaxService" in both code and config file together.
    [ServiceContract]
    public interface IAjaxService
    {
        [OperationContract]
        [WebInvoke(Method="POST",
            RequestFormat=WebMessageFormat.Json,
            ResponseFormat=WebMessageFormat.Json,
            BodyStyle=WebMessageBodyStyle.Wrapped)]
        User CreateJsonUser(int id, string name, string address, string phoneNumber);


        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Xml,
            BodyStyle = WebMessageBodyStyle.Wrapped)]
        User CreateXmlUser(int ID, string name, string address, string phoneNumber);
    }
}

服务实现代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;

namespace WCF_AjaxService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "AjaxService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select AjaxService.svc or AjaxService.svc.cs at the Solution Explorer and start debugging.
 
    public class AjaxService : IAjaxService
    {
        public User CreateJsonUser(int id, string name, string address, string phoneNumber)
        {
            return new User() { ID=id, Address= address, Name = name, PhoneNumber = phoneNumber};
        }

        public User CreateXmlUser(int id, string name, string address, string phoneNumber)
        {
            return new User() { ID = id, Address = address, Name = name, PhoneNumber = phoneNumber };
        }
    }
}
 
  
配置文件代码: 
其中绑定类型必须为webHttpBinding方式才能支持Ajax访问,且必须在在endpoint behavior 中设置WebHttp节点。



  
    
  
  
    
    
      
        
          
          
          
          
        
      

      
        
          
        
      
    

    
      
        
      
    
    
    
  
 
    
    
    
  




 
  
前端HTML代码:



    
    
    


    
    
    
   
   

你可能感兴趣的:(WCF)