0

我正在学习 WCF 服务。我正在尝试从 Jquery 调用 RESTful 服务。我的服务如下

服务等级

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

namespace RESTfulServiceLib
{
[AspNetCompatibilityRequirements(RequirementsMode
    = AspNetCompatibilityRequirementsMode.Allowed)]
public class RestFullService : IRestFullService
{
    public string Welcome(string Name)
    {
        return  "Welcome to Restful Service " + Name;
    }
}
}

界面

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

namespace RESTfulServiceLib
{

[ServiceContract]

public interface IRestFullService
{
    [OperationContract]
    [WebInvoke(UriTemplate="/Welcome/{Name}",Method="GET",ResponseFormat=WebMessageFormat.Json)]
    string Welcome(string Name);
}
}

我创建了一个服务主机,svc 文件是这样的

<%@ ServiceHost Language="C#" Debug="true" Service="RESTfulServiceLib.RestFullService" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

我有以下配置设置

<configuration>

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

<system.serviceModel>
    <behaviors>
        <endpointBehaviors>
            <behavior name="EndPBhvr">
                <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
                    faultExceptionEnabled="true" />

            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="SvcBhvr">
                <serviceMetadata httpGetEnabled="true" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
    <services>
        <service name="RESTfulServiceLib.RestFullService">
            <endpoint address="" behaviorConfiguration="EndPBhvr"
                binding="webHttpBinding" bindingConfiguration="" name="EP1"
                contract="RESTfulServiceLib.IRestFullService" />
        </service>
    </services>
</system.serviceModel>
</configuration>

运行应用程序后,当我浏览网址“http://localhost:2319/RESTFullService.svc/welcome/Mahesh”时,它返回的值为

"Welcome to Restful Service Mahesh"

我曾尝试使用 Jquery 调用此服务。但我越来越

error 200 undefined

脚本如下

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.4.min.js"></script>
<script >
function ajaxcall()
{
    $.ajax({
        url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType:"jsonp",
        data:{},
        processdata : true,
        success: function(response)
        {
            var data= response.d;
            alert(data);
        },

        error: function(e)
        {
            alert('error '+e.status + ' ' + e.responseText);
        }
    });
}
$().ready(function(){
    $('#btntest').click(ajaxcall);
})  
</script>
</head>
<body>
<button id="btntest" >Click Me</button>
</body>
</html>

我的编码有什么问题?请帮我...

谢谢

马赫什

4

3 回答 3

1

在您使用的 jQuery 的成功中

// var data= response.d;

但您没有返回有效的 json。您的回复中没有“d”。

于 2012-12-07T05:41:35.833 回答
0

这是由于跨域问题。我在配置文件中做了一些更改,效果很好

修改后的配置文件。添加了带有 crossDomainScriptAccessEnabled="true" 的新绑定配置并添加到端点。并把 aspNetCompatibilityEnabled="false"

<configuration>

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

<system.serviceModel>
    <standardEndpoints />
    <bindings>
        <webHttpBinding>
            <binding name="Bind1" crossDomainScriptAccessEnabled="true" />
        </webHttpBinding>
    </bindings>
    <behaviors>
        <endpointBehaviors>
            <behavior name="EndPBhvr">
                <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"
                    faultExceptionEnabled="true" />
            </behavior>
        </endpointBehaviors>
        <serviceBehaviors>
            <behavior name="SvcBhvr">
                <serviceMetadata httpGetEnabled="false" />
            </behavior>
        </serviceBehaviors>
    </behaviors>
       <serviceHostingEnvironment aspNetCompatibilityEnabled="false" />
    <services>
        <service behaviorConfiguration="SvcBhvr" name="RESTfulServiceLib.RestFullService">
            <endpoint address="" behaviorConfiguration="EndPBhvr" binding="webHttpBinding"
                bindingConfiguration="Bind1" name="EP1" contract="RESTfulServiceLib.IRestFullService" />
        </service>
    </services>
</system.serviceModel>
</configuration>

修改后的脚本,我添加了“?callback=?” 在 URL 的末尾以 JSON 格式而不是 JSONP 格式获取输出。JSONP 无需在 URL 中提供回调即可工作

<!DOCTYPE html>
<html>
<head>
<script src="jquery-1.6.4.min.js"></script>
<script type="text/javascript" language="javascript">
    function ajaxcall()
    {
        $.ajax({
            url: "http://localhost:2319/RESTFullService.svc/welcome/mahesh?calback=?",
            type: "GET",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: {},
            processdata: true,
            success: function (response) {
                var data = response;
                alert(data);
            },

            error: function (e) {
                alert('error ' + e.status + ' ' + e.responseText);

            }
            });
    }

    $().ready(function(){
        $('#btntest').click(ajaxcall);
    })  
</script>
</head>
<body>
    <button id="btntest" >Click Me</button>
</body>
</html>

感谢我在 Calsoft Labs 的同事 Mrs.Poorani 帮助我解决了这个问题

于 2012-12-12T13:14:26.900 回答
0
function CallService(sucessData) {
$.ajax({
    // Add code for Cross Domain
    headers: getHeaders(),
    type: varType, //GET or POST or PUT or DELETE verb
    url: varUrl, // Location of the service
    data: varData, //Data sent to server
    contentType: varContentType, // content type sent to server
    dataType: varDataType, //Expected data format from server
    processdata: varProcessData, //True or False
    crossDomain: true,
    cache: varCache,
    timeout: 200000,
    success: sucessData,
    error: function (xhr) {// When Service call fails
        fancyAlert("Error: " + xhr.responseText);
        //fancyAlert('Error occured in Service Call');
    }
});
}
于 2014-06-06T07:31:00.820 回答