【问题标题】:jquery ajax call to .NET web api returns errorjquery ajax 调用 .NET web api 返回错误
【发布时间】:2013-10-01 08:21:49
【问题描述】:

我正在测试一个简单的 ApiController:

namespace SMOnline.Controllers
{
    public class DocumentosController : ApiController
    {
        Documentos[] docs = new Documentos[] 
        { 
            new Documentos { ID = 1, Tipo = 1, Designacao = "FC001"}, 
            new Documentos { ID = 2, Tipo = 1, Designacao = "FC002"}
        };

        public IEnumerable<Documentos> GetAll()
        {
            return docs;
        }
    }
}

在客户端,我从不同的域调用它

$.ajax({
    async: true,
    type: 'GET', //GET or POST or PUT or DELETE verb
    url: apiUrl + 'Documentos/', // Location of the service
    dataType: 'jsonp', //Expected data format from server
})
.done(function (data) {
    // On success, 'data' contains a list of documents.
    $.each(data, function (key, item) {
       alert(item.Designacao);
    })
})
.fail(function (jqxhr, textStatus, error) {
    alert(textStatus + " " + error);
});

我的问题是 JSONP 请求总是返回错误

parsererror 错误:没有调用 jQuery20301899278084596997_1380125445432

我一直在搜索,但仍然没有找到解决方案。

编辑: 我忘了提到使用提琴手返回的值似乎正确的标题是 200 并且内容是 JSON 数组。

【问题讨论】:

  • jsonp 应该在服务器端处理。在服务器端你在哪里做这样的事情:return "myCallBack("+data+");"
  • @RoyiNamir 无论如何我可以知道在服务器端创建的自动回调值是什么?
  • @RoyiNamir 无法使用它,但我找到了解决方案。

标签: c# jquery callback asp.net-web-api jsonp


【解决方案1】:

查看WebApiContrib.Formatting.Jsonp 以正确处理您的 JSONP 调用。

在包管理器控制台上:

Install-Package WebApiContrib.Formatting.Jsonp

【讨论】:

    【解决方案2】:

    通过创建一个 ActionFilterAttribute 解决了这个问题。我在此线程JSONP with ASP.NET Web API 010227leo 的答案中找到了解决方案

    【讨论】:

      【解决方案3】:

      为了能够在 web api 中使用不同的输出格式,您必须在 FormatterConfig 中注册适当的格式化程序。 还将contentType: "application/json" 添加到您的ajax 调用中。 更详细的解释可以看here

      【讨论】:

        猜你喜欢
        • 2014-08-07
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 2020-10-27
        • 2016-01-07
        • 2016-03-11
        • 1970-01-01
        相关资源
        最近更新 更多