3

我正在尝试从我的 webapi 服务器获取数据。调试显示

GET http://localhost:62578/api/DB [HTTP/1.1 200 OK 2ms]

但我没有成功,而是我遇到了错误并且没有数据传递给错误函数?

var records;
var loadedData = new Array();

$.ajax({
    type: 'GET',
    dataType: 'json',  
    accept: "application/json",
    url: 'http://localhost:62578/api/DB',
    //data: { a:'a' },
   // contentType: 'application/json; charset=utf-8',
    success: function(data) {
    //I never get here.
        $.each(data, function (key, val) {//key is the row number, val is the  object data below
                $.each(val, function (key2, val2) {//key2 is the array element name, val2 is the data. 
                    if (key == 0) loadedData.push(key2);  //we only need one row of collumns
                });
                records = key;
                init(loadedData);   
                });
            },
             error: function(jqXHR, exception) {
            //both return undefined.
        }
        });

webapi 服务器日志。

jttp = http 仅供参考(愚蠢的堆栈溢出)

iisexpress.exe Information: 0 : Request, Method=GET, Url=jttp://localhost:62578/api/DB, Message='jttp://localhost:62578/api/DB'
iisexpress.exe Information: 0 : Message='DB', Operation=DefaultHttpControllerSelector.SelectController
iisexpress.exe Information: 0 : Message='MvcApplication1.Controllers.DBController', Operation=DefaultHttpControllerActivator.Create
iisexpress.exe Information: 0 : Message='MvcApplication1.Controllers.DBController', Operation=HttpControllerDescriptor.CreateController
iisexpress.exe Information: 0 : Message='Selected action 'GetAllProducts()'', Operation=ApiControllerActionSelector.SelectAction
iisexpress.exe Information: 0 : Operation=HttpActionBinding.ExecuteBindingAsync
iisexpress.exe Information: 0 : Message='Action returned 'MvcApplication1.Models.DataBase[]'', Operation=ReflectedHttpActionDescriptor.ExecuteAsync
iisexpress.exe Information: 0 : Message='Will use same 'JsonMediaTypeFormatter' formatter', Operation=JsonMediaTypeFormatter.GetPerRequestFormatterInstance
iisexpress.exe Information: 0 : Message='Selected formatter='JsonMediaTypeFormatter', content-type='application/json; charset=utf-8'', Operation=DefaultContentNegotiator.Negotiate
iisexpress.exe Information: 0 : Operation=ApiControllerActionInvoker.InvokeActionAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Operation=DBController.ExecuteAsync, Status=200 (OK)
iisexpress.exe Information: 0 : Response, Status=200 (OK), Method=GET, Url=jttp://localhost:62578/api/DB, Message='Content-type='application/json; charset=utf-8', content-length=unknown'
iisexpress.exe Information: 0 : Operation=JsonMediaTypeFormatter.WriteToStreamAsync
iisexpress.exe Information: 0 : Operation=DBController.Dispose
4

1 回答 1

0

我认为您的 javascript 代码位于不同的端口;可能是端口 80,而您的 json 请求位于端口 62578。Ajax 请求只允许在相同的域、协议和端口中。

为了解决您的问题,您需要使用 JSONP 数据类型或任何其他类似机制(服务器端解决方案)。

查看wikipedia以获取有关 JSONP 的更多信息。

查看此示例,了解如何将 JSONP 与 jQuery ajax 调用一起使用。

查看stackoverflow以了解类似问题。

于 2013-03-14T17:34:29.110 回答