2014-02-07 3 views
1

Jquery Ajax 용 JSON에 WCF 서비스를 가져 오려고하지만 메서드가 시작되지 않아도 오류 요청이 반환됩니다.불량 요청 요청 WCF 서비스 Jquery Ajax

다음은 서비스를 호출하는 Java 스크립트 코드입니다. 서비스 클래스, 서비스 클래스, 서비스 Web.config, Global.asax 서비스입니다.

$ .getJSON의 GetData 메소드가 작동하지만 $ .Ajax가 아닌 경우에 세부 정보가 표시됩니다.

이미 AddStudant 메서드를 사용하면 어떻게 든 작동하지 않습니다.

아무도 저에게 무슨 말을하는 데 도움이 될까요?

자바 스크립트

$ ("#의 BT ')을 클릭 (함수() {

var에 URL ="http://domain.net/Service1.svc/AddStudant "; var에 데이터 = {"ID ". 1" 이름 ":"에릭슨 알베스 "}; var에 jdata = {}; jdata.student = 데이터,

callAjax (URL, 'JSON', 'POST', 기능 (결과) { 경고 (결과); }, JSON.stringify (jdata) ); });

함수 callAjax (ajaxUrl, ajaxDataType, ajaxType, funcSucess, dataValues) {

$.ajax({ 
     url: ajaxUrl, 
     dataType: ajaxDataType, 
     type: ajaxType, 
     data: dataValues, 
     processdata: true, 
     contentType: "application/json;charset-uf8" 
    }) 
     .done(function (data) { 
      funcSucess(data); 
     }) 
     .always(function (data) { 

     }).fail(function (xhr, status, errorThrown) { 
      alert(xhr.responseText); 
     }); 
} 

인터페이스

[ServiceContract] 
    public interface IService1 
    { 
     [OperationContract] 
     [WebInvoke(Method = "GET", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     ResponseFormat = WebMessageFormat.Json)] 
     Student GetData(int id); 

     [OperationContract] 
     [WebInvoke(Method = "POST", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json)] 
     Student AddStudant(Student student); 

    } 

[DataContract] 
    public class Student 
    { 
     [DataMember] 
     public int ID { get; set; } 
     [DataMember] 
     public string Name { get; set; } 
    } 

서비스 클래스

[AspNetCompatibilityRequirements(RequirementsMode 
    = AspNetCompatibilityRequirementsMode.Allowed)] 
    public class Service1 : IService1 
    { 
     [WebInvoke(Method = "GET", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     ResponseFormat = WebMessageFormat.Json)] 
     public Student GetData(int id) 
     { 
      return new Student() { ID = id, Name ="Ericsson Alves" }; 
     } 

     [WebInvoke(Method = "POST", 
     BodyStyle = WebMessageBodyStyle.WrappedRequest, 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json)] 
     public Student AddStudant(Student student) 
     { 
      return new Student() { ID = student.ID , Name ="Ericsson Alves" }; 
     } 
    } 

의 Web.config 서비스

<?xml version="1.0"?> 
<configuration> 

    <appSettings> 
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" /> 
    </appSettings> 
    <system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5"/> 
    </system.web> 
    <system.serviceModel> 

    <bindings> 
     <webHttpBinding> 
     <binding name="WebHttpBdg" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" /> 
     </webHttpBinding> 
    </bindings> 

    <behaviors> 
     <serviceBehaviors> 
     <behavior name="BehaviorDefault"> 
      <serviceMetadata httpGetEnabled="true" /> 
      <serviceDebug includeExceptionDetailInFaults="true" /> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="AJAXWCFServiceAspNetAjaxBehavior"> 
      <webHttp defaultOutgoingResponseFormat="Json" automaticFormatSelectionEnabled="true" /> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 

    <services> 
     <service name="TestWCFJsonAjax.Service.Service1" behaviorConfiguration="BehaviorDefault"> 
     <endpoint address="" binding="webHttpBinding" bindingConfiguration="WebHttpBdg" 
        behaviorConfiguration="AJAXWCFServiceAspNetAjaxBehavior" 
      name="Service1" contract="TestWCFJsonAjax.Service.IService1" /> 
     <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> 
     </service> 
    </services> 

    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
     multipleSiteBindingsEnabled="true" /> 

    <standardEndpoints> 
     <webHttpEndpoint> 
     <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true" crossDomainScriptAccessEnabled="true" /> 
     </webHttpEndpoint> 
    </standardEndpoints> 

    </system.serviceModel> 

    <system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    <directoryBrowse enabled="true"/> 
    <httpProtocol> 
     <customHeaders> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
     <add name="Access-Control-Allow-Headers" value="Content-Type" /> 
     <!--<add name="Access-Control-Allow-Methods" value="GET, POST, OPTIONS" />--> 
     </customHeaders> 
    </httpProtocol> 
    </system.webServer> 

</configuration> 

Global.asax에 서비스

public class Global : System.Web.HttpApplication 
    { 

     protected void Application_Start(object sender, EventArgs e) 
     { 
      RouteTable.Routes.Add(new ServiceRoute("", new WebServiceHostFactory(), typeof(Service1))); 
     } 
     protected void Application_BeginRequest(object sender, EventArgs e) 
     { 
      //HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache); 
      //HttpContext.Current.Response.Cache.SetNoStore(); 

      //EnableCrossDmainAjaxCall(); 
      HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); 
      if (HttpContext.Current.Request.HttpMethod == "OPTIONS") 
      { 
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST"); 
       HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); 
       HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); 
       HttpContext.Current.Response.End(); 
      } 
     } 
    } 

답변

0

jdata 대신 data를 보내보십시오, 나는 그것이 { "ID": 1, "Name": "Ericsson Alves" } 대신처럼 개체를 보낼 필요가 가정 현재 수행중인 다른 객체 내부로 전송 {student: { "ID": 1, "Name": "Ericsson Alves" }}

1

ajax 요청 내에서 contentType ~ text/plain을 설정하십시오.

+2

왜 이것이 해결책인지 설명해주십시오. –

+0

이것이 해결책입니다. 감사합니다. –