简体   繁体   English

Ajax请求WCF数据(采用JSON格式)但是成功消息出错

[英]Ajax requesting WCF data (in JSON format) but reaching error with success message

I've been trying to resolve my issue with this answer but I'm having no luck. 我一直试图用这个答案解决我的问题,但我没有运气。

Overall, I've created a WCF project with a number of functions in which I would like to access via AJAX (via javascript in my html page). 总的来说,我已经创建了一个WCF项目,其中包含许多我希望通过AJAX访问的函数(通过我的html页面中的javascript)。

Here's an example of a function within my web service: 这是我的Web服务中的一个函数示例:
iService iService

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

Service 服务

    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;
    }

Please note that I have also tried returning the Stream directly also. 请注意,我也尝试直接返回Stream

Over to my javascript and ajax! 到我的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);
      }
   });
}

I hit the error section, but strangely with a success error message... 我点击错误部分,但奇怪的是成功错误消息...

错误信息

I originally thought the issue was because the JSON from the external API was incorrectly formatted, but I tried changing my web service to return some perfectly valid JSON and the same error was displayed. 我最初认为问题是因为外部API的JSON格式不正确,但我尝试更改我的Web服务以返回一些完全有效的JSON,并显示相同的错误。 Like I mentioned also, I tried changing my webservice to return the Stream but I had no luck. 就像我提到的那样,我尝试更改我的webservice以返回Stream,但我没有运气。

Any help with this would be appreciated and I would be very grateful. 对此有任何帮助将不胜感激,我将非常感激。

Updates 更新

PS It appears to work fine in WCF Test Client, returning a string with what I expect. PS它似乎在WCF测试客户端正常工作,返回一个我期望的字符串。
PPS Just added another parameter to the error function to get its status, I'm getting parsererror PPPS The 3rd parameter passed to error is jquery171014696656613195724_1341477967656 was not called PPS刚刚在错误函数中添加了另一个参数来获取其状态,我得到了parsererror PPPS传递给错误的第3个参数是jquery171014696656613195724_1341477967656 was not called

Just a quick guess: You're using WebInvokeAttribute but trying to call a service operation using HTTP GET. 只是一个简单的猜测:您正在使用WebInvokeAttribute但尝试使用HTTP GET调用服务操作。 Default value for Method property of the WebInvokeAttribute is POST ( MSDN ). WebInvokeAttribute Method属性的默认值是POSTMSDN )。 Try switching to WebGetAttribute : 尝试切换到WebGetAttribute

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

Alternatively you can set the Method property of the WebInvokeAttribute to GET . 或者,您可以将WebInvokeAttributeMethod属性设置为GET

UPDATE UPDATE

As @Cheeso mentioned, the "Parse error" that you get is due to the fact that the JavaScript engine cannot interpret the data that you're returning because it's just a plain JSON which itself is not a valid expression (imagine that you put it inside the <script></script> tags. This obviously won't work and this is exactly what the browser tries to do). 正如@Cheeso所提到的,你得到的“解析错误”是因为JavaScript引擎无法解释你要返回的数据,因为它只是一个普通的JSON,它本身不是一个有效的表达式(假设你把它放了在<script></script>标签内。这显然不起作用,这正是浏览器尝试做的事情)。

You need to respect the callback parameter and wrap you response so it becomes a parameters of the function whose name is passed via callback parameter: 您需要尊重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);

Alternatively just set the "dataType" to "json" when making AJAX call. 或者,只需在进行AJAX调用时将“dataType”设置为“json”。

You have dataType : 'jsonp' in your jquery code. 你的jquery代码中有dataType : 'jsonp' This tells jQuery to append a callback=XXXX to the URL. 这告诉jQuery将一个callback=XXXX附加到URL。

The server-side of this dialogue needs to wrap the JSON result in that callback. 此对话框的服务器端需要将JSON结果包装在该回调中。 But your code doesn't do that. 但是你的代码不会这样做。

Are you sure you want jsonp? 你确定要jsonp吗?

You might be able to fix this by using dataType: 'json' 您可以通过使用dataType: 'json'来解决这个问题dataType: 'json'

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

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