3

我一直在尝试用这个答案解决我的问题解决我的问题,但我没有运气。

总的来说,我创建了一个 WCF 项目,其中包含许多我想通过 AJAX 访问的功能(通过我的 html 页面中的 javascript)。

这是我的 Web 服务中的一个函数示例:
iService

[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();

服务

    public string GetStuff()
    {
        string url = string.Format("http://myapi.co.uk/api/mystuff");

        WebRequest myReq = WebRequest.Create(url);

        // Where USERNAME and PASSWORD are constants
        string usernamePassword = USERNAME + ":" + PASSWORD;
        CredentialCache mycache = new CredentialCache();
        mycache.Add(new Uri(url), "Basic", new NetworkCredential(USERNAME, PASSWORD));
        myReq.Credentials = mycache;
        myReq.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new ASCIIEncoding().GetBytes(usernamePassword)));

        WebResponse wr = myReq.GetResponse();
        Stream receiveStream = wr.GetResponseStream();

        StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8);
        string content = reader.ReadToEnd();

        return content;
    }

请注意,我也尝试过退回Stream直接返回。

转到我的 javascript 和 ajax !

function getData()
{
  jQuery.support.cors = true;

  $.ajax({
      type: "GET",
      url: "http://localhost:15574/Service1.svc/GetStuff",
      contentType: "application/json; charset=utf-8",
      dataType: "jsonp",
      success: function(result) {
         alert(result);
      },
      error: function(msg) {
        alert("Fail: " + msg.status + ":" + msg.statusText);
      }
   });
}

我点击了错误部分,但奇怪的是成功错误消息......

错误信息

我最初认为这个问题是因为来自外部 API 的 JSON 格式不正确,但我尝试更改我的 Web 服务以返回一些完全有效的 JSON,并显示了相同的错误。就像我也提到的那样,我尝试更改我的网络服务以返回 Stream,但我没有运气。

对此的任何帮助将不胜感激,我将不胜感激。

更新

PS 它似乎在 WCF 测试客户端中工作正常,返回一个符合我期望的字符串。
PPS 刚刚在错误函数中添加了另一个参数以获取其状态,我正在获取parsererror PPPS 传递给错误的第三个参数是jquery171014696656613195724_1341477967656 was not called

4

2 回答 2

1

只是一个快速的猜测:您正在使用WebInvokeAttribute但尝试使用 HTTP GET 调用服务操作。Method属性的默认值WebInvokeAttributePOST( MSDN )。尝试切换到WebGetAttribute

[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string GetStuff();

或者,您可以将 的Method属性设置WebInvokeAttributeGET

更新

正如@Cheeso 提到的,你得到的“解析错误”是由于 JavaScript 引擎无法解释你返回的数据,因为它只是一个普通的 JSON,它本身不是一个有效的表达式(想象你把它在<script></script>标签内。这显然是行不通的,这正是浏览器试图做的)。

您需要尊重callback参数并包装您的响应,使其成为名称通过参数传递的函数的callback参数:

// If the ASP.NET compatibility was enabled, you could safely use HttpContext.Current
// It's here just to demonstrate the idea
return string.Format("{0}({1});", HttpContext.Current.Request.QueryString["callback"], content);

或者,在进行 AJAX 调用时将“dataType”设置为“json”。

于 2012-07-04T14:48:54.870 回答
1

你有dataType : 'jsonp'你的jQuery代码。这告诉 jQuery 将 a 附加callback=XXXX到 URL。

此对话的服务器端需要将 JSON 结果包装在该回调中。但是您的代码没有这样做。

你确定要jsonp吗?

您也许可以通过使用来解决此问题dataType: 'json'

于 2012-07-04T16:57:24.690 回答