【问题标题】:json callback error was not called wcf jqueryjson回调错误未调用wcf jquery
【发布时间】:2013-03-23 01:19:11
【问题描述】:

我有 WCF 服务:

[ServiceContract]

public interface IMunicipiosService
{
    [OperationContract]
    [WebInvoke(Method = "GET",
        ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped,
        UriTemplate = "ListaMunicipios")]

    List<ClsListaMunicipios> GetListaMunicipios();
}

它在chrome中返回json(是JSON还是JSONP?):

{"GetListaMunicipiosResult":[{"MunicipioID":"1","MunicipioNome":"Florianopolis","MunicipioUf":"SC"},{"MunicipioID":"2","MunicipioNome":"Joinville","MunicipioUf":"SC"}]}

我的 JS:

$.ajax("http://localhost:56976/MunicipiosService.svc/ListaMunicipios", {

    beforeSend: function (xhr) {
        // $.mobile.showPageLoadingMsg();
        alert('beforeSend');
    },

    complete: function () {
        // $.mobile.hidePageLoadingMsg();
        alert('complete');
    },
    contentType: 'application/json; charset=utf-8',
    dataType: 'jsonp',
    type: 'GET',
    data: {},

    error: function (xhr, ajaxOptions, thrownError) {
        alert('not ok 1 ' + xhr.status);
        alert('not ok 2 ' + xhr.responseText);
        alert('not ok 3 ' + thrownError);
    },
    success: function (data) {
        alert('success');

    }
});

但我得到了错误:

不行 1200

不好 2 未定义

不正常 3 错误 jQueryXXXXXXXXX 未被调用

【问题讨论】:

  • 除非您正在执行跨域 ajax 请求,否则您不应指定 jsonp。您应该将 dataType 选项更新为 json
  • @awbergs,我将 dataType: 'jsonp' 更改为 dataType: 'json' 现在我得到: 不行 1 0 不行 2 不行 3
  • 当我在 index.html 中调用 $.ajax(... 时工作正常。我不知道为什么调用在 .js 文件中不起作用。
  • 您是否将 JS 文件托管在“localhost”域上?此外,由于您没有发送任何数据,因此没有任何理由在 ajax 选项中设置 contentType。另外,如果您可以发布可能有帮助的服务方法 impl。

标签: jquery .net json wcf cordova


【解决方案1】:

由于您能够通过 Chrome 发出的 GET 请求获得 JSON 响应,因此我假设您已正确设置 WCF 服务。

您唯一的问题是您的成功回调没有触发。如果您正在执行跨域请求但只是从 WCF 方法返回 JSON,则会发生这种情况。你需要一些东西来构造和流回响应。

不要简单地返回List&lt;ClsListaMunicipios&gt;,而是考虑在你的服务方法中这样做:

    HttpContext.Current.Response.ClearContent();

    HttpContext.Current.Response.ContentType = "application/json";
    string callback = HttpContext.Current.Request.QueryString["callback"];

    HttpContext.Current.Response.Write(callback + "( " + new JavaScriptSerializer().Serialize(YourListObjectGoesHere)  + " )");
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();

我使用了您的 AJAX 调用,随后触发了成功回调。

【讨论】:

    猜你喜欢
    • 2014-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 2012-06-30
    • 2014-01-08
    • 2012-05-14
    • 2011-09-30
    相关资源
    最近更新 更多