Skip to main content
 首页 » 编程设计

c#之使用 C# 和 WFC 的跨域 jQuery Ajax

2024年01月02日42bonelee

我有一个用 C# 和 WCF 编写的小型网络服务。

[WebService(Namespace = "http://tempuri.org/")] 
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
[System.Web.Script.Services.ScriptService] 
public class Service1 : System.Web.Services.WebService 
{ 
    [WebMethod] 
    public string HelloWorld() 
    { 
        return "Hello Worlds"; 
    } 
} 

我有一些 jQuery 代码;

        $.support.cors = true; 
 
        $.ajax({ 
            type: "POST", 
            url: "http://localhost:61614/Service1.asmx/HelloWorld", 
            data: '{}', 
            dataType: "json", 
            success: function (msg) { 
                alert(0); 
            }, error: function (a, b, c) { alert("Err:" + c );  
            } 
        }); 

这会调用网络服务。调用没有问题,但返回时出错。

网络服务在一个应用程序中,而网页本身就是一个简单的 HTML 页面。最终,HTML 将在 PhoneGap 中使用。

我已经尝试了各种各样的事情。

添加 contentType: "application/json; charset=utf-8", 会导致整个调用失败。 使用 dataType: 'jsonp" 导致调用失败。

基本上,上面调用了 WS 但在返回时出错,这很奇怪。

我的要求是我需要从网络服务返回一个 JSON 对象,并且它必须在 Safari 中工作。

有人有完整的 JSONP 调用示例代码吗?

请您参考如下方法:

来自 jQuery getJSON :

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

为了将您的请求视为 JSONP 请求,您需要在您的 URL 中包含 callback=?。这告诉 jQuery 创建一个回调函数并将该函数的名称作为回调参数传递给您的服务器。

在服务器端代码中,您的方法必须返回 JSON 代码包装或填充,其中 JavaScript 函数的名称作为查询字符串中的回调参数传入。

本质上,您所做的是将 JavaScript 返回到客户端浏览器,它会立即运行,并调用已在页面上下文中定义的函数。

JavaScript:

$.getJSON("http://localhost:61614/Service1.asmx/HelloWorld?callback=?", 
    function(data) { 
 
        // alert raw JSON data 
        alert(JSON.stringify(data)); 
 
        // access the "say" property and alert it 
        alert(data.say); 
    } 
); 

服务器端:

这是您需要在服务器端执行的操作的粗略版本:

// get the callback parameter value and assign to the String callback 
... 
return callback + "( { 'say' : 'HelloWorld' } );"; 

对引擎盖下发生的事情的进一步技术解释:

虽然这不是您今天需要了解的内容,但这可能会帮助您更多地了解 jQuery 如何实现 JSONP。

计算结果可能如下所示:

return "jquery43214321432143242({'say':'HelloWorld'});" 

其中 jquery43214321432143242 是为您的成功回调函数指定的随机名称。同样,由于返回的文本是使用 text/javascript 返回的,它会立即运行,将 {'say':'HelloWorld'} 对象作为参数传递给函数。

生成的输出应该是代表原始 JSON 的警告消息,以及从 .say 属性中提取的单词“HelloWorld”。