我在本地机器上托管了一个简单的 MVC Web api,它所做的只是Personnel
以 JSON 格式返回对象。在同一台机器上,我有一个简单的 html 页面,它试图使用getJSON()
.
getJSON
尽管响应成功返回,服务器和客户端是同一台机器,并且 JSON 有效,但调用失败并出现以下错误。
parsererror Error: jQuery110206749425150919706_1382127977754 was not called
在控制器...
// GET api/personnel
public List<Personnel> Get()
{
return GetPersonnel();
}
GetPersonnel()
只返回一个Personnel
对象列表
public class Personnel
{
public String FirstName { get; set; }
public String LastName { get; set; }
public String RoomNumber { get; set; }
}
添加到 Application_Start() 以确保仅返回 JSON...
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());
这是我用来调用这个 API 的 jQuery(在同一个盒子上)。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.ajaxSetup({ async:false});
$(document).ready(function () {
$("button").click(function () {
var api = "http://localhost:13131/DirectoryServicePool/api/personnel?callback=?"; // this api doesn't work
//api = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; // this api does
$.getJSON(api, {
format: "json"
}, function (result) {
alert("GotJSON");
}).fail(function (XHR, status, error) {
alert(status + ' ' + error);
});
});
});
</script>
</head>
<body><button>Get JSON data</button></body>
</html>
fiddler 中的响应(JSON 有效)...
HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Oct 2013 20:08:48 GMT
Content-Length: 244
[{"FirstName":"1","LastName":"5","RoomNumber":"6"},{"FirstName":"2","LastName":"5","RoomNumber":"6"},{"FirstName":"3","LastName":"5","RoomNumber":"6"},{"FirstName":"4","LastName":"5","RoomNumber":"6"}]
提前致谢。