简体   繁体   English

通过Jquery Ajax消耗WCF JSON数据

[英]Consuming WCF JSON data via Jquery Ajax

I have a WCF service hosted in IIS and returns JSON data properly when called through a browser. 我在IIS中托管了WCF服务,并且通过浏览器调用时可以正确返回JSON数据。

I'm trying to consume the service via Jquery Ajax call. 我正在尝试通过Jquery Ajax调用使用服务。 Both WCF and Jquery app are in same domain. WCF和Jquery应用程序都在同一域中。

I have checked comments for a similar question : 我已经检查了类似问题的评论:

Consuming a WCF Service in jQuery via AJAX Call in a different Project (Cross Domain) , unfortunately i could solve my problem from above. 通过AJAX在另一个项目(跨域)中通过AJAX调用消耗WCF服务 ,不幸的是我可以从上面解决我的问题。

My WCF Service Web.config 我的WCF服务Web.config

<system.serviceModel>
    <services>
      <service name="MyWCFService.Service1" behaviorConfiguration="MyWCFService.Service1Behavior">

        <endpoint address="Service1" 
                   binding="basicHttpBinding" 
                  contract="MyWCFService.IService1"/>

        <endpoint address="../Service1.svc"
                  binding="webHttpBinding"
                  contract="MyWCFService.IService1"
                  behaviorConfiguration="webBehaviour" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyWCFService.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

Method Signature: 方法签名:

[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetEmployeeIDs/{value}")]
List<Employee> GetEmployeeIDs(String value);

Employee Class : 员工类别:

[DataContract]
public class Employee
{
    [DataMember]
    public string ID { get; set; }
}

Data returned when i hit below URL from broswer 当我点击浏览器中的URL下方时返回的数据

URL : http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984

Result from Browser : 
{"GetEmployeeIDsResult":[{"ID":"239840"},{"ID":"239841"},{"ID":"239842"},{"ID":"239843"},{"ID":"239844"},{"ID":"239845"},{"ID":"239846"},{"ID":"239847"},{"ID":"239848"},{"ID":"239849"}]}

Jquery Call: jQuery调用:

function Call_WCF_JSON() {
            var result = ""
            var ArgValue = '23984';

            $.getJSON("http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984", {},
                    function(data) {
                        alert(data);
                        console.log(data);

                });

            //GetEmployeeIDs is a function which has Value as String Argument  
            $.ajax({
                type: "GET",
                url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs",
                async: false,
                data: '{"value":"' + ArgValue + '"}',                    
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    var oObj;
                    oObj = jQuery.parseJSON(data);
                    alert(oObj);
                    console.log(oObj);

                    var oRealObj;
                    oRealObj = jQuery.parseJSON(oObj.GetEmployeeIDsResult);
                    alert(oRealObj);
                    console.log(oRealObj);
                },
                failure: function (response) {
                    alert(response);
                    console.log(response);
                }
            });
        }

Edit 1 : Entire App is recreated with below code 编辑1:使用以下代码重新创建整个应用程序

Webconfig File with Single JSON Binding 具有单个JSON绑定的Webconfig文件

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

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <services>
      <service name="Emp_JSON_Srvc.Service1" behaviorConfiguration="Emp_JSON_Srvc.Service1Behavior">
        <endpoint address="../Service1.svc"
                  binding="webHttpBinding"
                  contract="Emp_JSON_Srvc.IService1"
                  behaviorConfiguration="webBehaviour" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Emp_JSON_Srvc.Service1Behavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="webBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

 </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>

</configuration>

Interface Code: 接口代码:

namespace Emp_JSON_Srvc
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "GetEmployeeIDs/{value}")]
        List<Employee> GetEmployeeIDs(String value);
    }

    [DataContract]
    public class Employee
    {
        [DataMember]
        public string ID { get; set; }
    }
}

Service Class 服务等级

namespace Emp_JSON_Srvc
{
    public class Service1 : IService1
    {

        public List<Employee> GetEmployeeIDs(String value)
        {
            List<Employee> results = new List<Employee>();
            results.Add(new Employee() { ID = "239840" });
            results.Add(new Employee() { ID = "239841" });
            results.Add(new Employee() { ID = "239842" });
            results.Add(new Employee() { ID = "239843" });
            results.Add(new Employee() { ID = "239844" });
            return results;
        }
    }
}

Result when i type URL in Browser 在浏览器中输入URL时的结果

URL : http://localhost:60529/Service1.svc/GetEmployeeIDs/98 
(I have fixed the port number in Visual Studio. hence it wont change for each run)

{"GetEmployeeIDsResult":[{"ID":"239840"},{"ID":"239841"},{"ID":"239842"},{"ID":"239843"},{"ID":"239844"}]}

Javascript to Consume Json 消费Json的Javascript

function Call_WCF_JSON() {

    var result = ""
    alert('Method 1 : Start');
    $.getJSON("http://localhost:60529/Service1.svc/GetEmployeeIDs/98", {},
            function (data) {
                alert(data);
                console.log(data);
            });

    alert('Method 2 : Start');
    var query = { sValue: '98' };
    $.ajax({
        type: "POST",
        url: "http://localhost:60529/Service1.svc/GetEmployeeIDs/98",
        data: JSON.stringify(query),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert("Method 2 : Success");
            /*
            for (var i = 0; i < data.length; i++) {
            alert(data[i].Name);
            }
            */
        },
        error: function (e) {
            alert('Method 2 : Error');
            alert('Method 2 : --> ' + e.responseText);
        }
    });

    alert('Method 3 : Start');
    var value = '98'
    $.ajax({
        type: "GET",
        url: "http://localhost:60529/Service1.svc/GetEmployeeIDs/98",
        cache: false,
        data: JSON.stringify(value),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        processData: true,
        success: function (msg) {
            alert("Method 3 : Success");
            alert(JSON.stringify(msg));
        },
        error: function (err) {
            alert('Method 3 : Error');
        }
    })

    alert('Method 4 : Start');
    var ArgValue = '98';
    $.ajax({
        type: "GET",
        url: "http://localhost:60529/Service1.svc/GetEmployeeIDs",
        async: false,
        data: '{"value":"' + ArgValue + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            alert("Method 4 : Success");
            var oObj;
            oObj = jQuery.parseJSON(data);
            alert(oObj);
            console.log(data);

            var oRealObj;
            oRealObj = jQuery.parseJSON(oObj.GetHostServersResult);
            alert(oRealObj);
            console.log(oRealObj);

            //alert(data.GetHostServersResult[0].Name);
        },
        failure: function (response) {
            alert('Method 4 : Error');
            alert(response);
        }
    });
}

and the result i get from javascript is 我从javascript中得到的结果是

Method 1 : Start
Method 2 : Start
Method 2 : Error
Method 2 : --> undefined
Method 3 : Start
Method 3 : Error
Method 4 : Start

any suggestions are appriciated. 任何建议都适用。

Thank you !! 谢谢 !!

this defaultOutgoingResponseFormat="Json" add

** **

   <endpointBehaviors>
   <behavior name="EndpointVehavior">
      <enableWebScript/>
      <webHttp defaultOutgoingResponseFormat="Json"/>
    </behavior>
  </endpointBehaviors>

** **

This is a stringified response. 这是一个严格的答复。 Try to do something like : 尝试做类似的事情:

var oObj;
oObj = jQuery.parseJSON(data);
var oRealObj;
oRealObj = jQuery.parseJSON(oObj.GetEmployeeIDsResult);

EDIT 编辑

I think the url that you provide the jQuery is wrong. 我认为您提供jQuery的网址是错误的。 this url: " http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984 ", should be like url: " http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs ", and 23984 should be ta data section of jQuery. 此网址:“ http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984 ”,应类似于网址:“ http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs ”,而23984应为jQuery的ta数据部分。

So as to Consume a WCF service I provide you with the following link : How to consume Wcf Service in javascript? 为了使用WCF服务,我为您提供了以下链接: 如何在javascript中使用Wcf服务?

EDIT 2 编辑2

ok.. Let's try this one. 好的..让我们尝试一下。

[OperationContract]
[WebInvoke(Method="POST",BodyStyle=WebMessageBodyStyle.Wrapped,ResponseFormat=WebMessageFormat.Json)]
List<Employee> GetEmployeeIDs(String value);

Now let's go to the client : 现在让我们去客户端:

var query = { sValue: '23984'};

$.ajax({
    type: "POST",
    url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs",
    data: data:JSON.stringify(query),,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        for(var i=0; i<data.length;i++){
              alert(data[i].ID);
        }
    },
    error: function (e) {
        alert(e.responseText);
        return;
    }
 });

You are using POST for a GET request. 您正在使用POST进行GET请求。 Try to change your ajax call to: 尝试将您的ajax调用更改为:

function Call_WCF_JSON() {
    var result = ""
    $.ajax({
        type: "GET",
        url: "http://MyServerDSN.com/MyWCFService/Service1.svc/GetEmployeeIDs/23984",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            console.log(data);
        },
        failure: function (response) {
            console.log("Error");
            console.log(response);
        }
    });
}

To show the console.log message use a debugger. 要显示console.log消息,请使用调试器。 For example firebug in Firefox or Chrome (just hit F12). 例如Firefox或Chrome中的萤火虫 (只需按F12键)。

EDIT: 编辑:
To debug AJAX request, have a look at the firebug console. 要调试AJAX请求,请查看firebug控制台。 There should be an Request like the following: 应该有一个类似以下的请求: 在此处输入图片说明 Check the HTTP-Status (yellow). 检查HTTP-Status (黄色)。 Is it 200, everything works fine. 是200,一切正常。 Then have a look into the response (you find it by clicking the + and navigate to the response tab). 然后查看响应(您可以通过单击+并找到响应选项卡找到它)。 What does it say? 它说什么? Please show us a screen of your firebug console if you still have problems. 如果仍有问题,请向我们显示Firebug控制台的屏幕。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM