跨域调用WCF服务

2023-12-07

我有一个 WCF 服务,这是我要调用的方法:

    [OperationContract]
    [WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
    double?[] GetPoints(string tourname);

我通过WCF测试客户端检查过,工作正常

所以我需要从html页面调用这个方法。它应该可以在跨域的其他计算机上工作。

我使用 jQuery 1-6-2.min.js 写了一些东西:

var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;

function CallService() {
        alert("CallService");
                $.ajax({
                    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
                    success       : function(msg) {//On Successfull service call
                    ServiceSucceeded(msg);                    
                    },
                    error: ServiceFailed// When Service call fails
                });
        }

function Start() {
    varType = "POST";
    varUrl = "http://localhost:1592/TourService.svc/GetPoints";
    varData = '{"tourname ":"customname"}';
    varContentType = "application/json; charset=utf-8";
    varDataType = "json";
    varProcessData = true; 
    CallService();
}

function ServiceSucceeded(result) {
    alert("ServiceSucceeded");
    alert(result);
}

function ServiceFailed(result) {
    alert('Service call failed: ' + result.status + ' ' + result.statusText);
    varType = null;
    varUrl = null;
    varData = null;
    varContentType = null;
    varDataType = null;
    varProcessData = null;
}

但是,调用 ServiceFailed 函数时会显示消息“服务调用失败 0 错误”

如何跨域调用WCF服务?(是否使用jQuery)

Thanks


基本上你需要使用 jSONP 而不是 jSON:

使用 jQuery 和 JSONP 与 WCF 服务进行跨域 AJAX

我将很快提供一个摘要,以防此链接消失。

另请参阅jQuery 文档有关如何使用 jSONP、jQuery 和 AJAX 的更多信息

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

跨域调用WCF服务 的相关文章

随机推荐