【发布时间】:2014-06-05 09:52:51
【问题描述】:
这是我在服务器中的控制器:
public class ChatController : ApiController
{
[HttpGet]
public HttpResponseMessage HelloWorld()
{
string result = "<h1>Hello world! Time is: " + DateTime.Now + "</h1>";
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(result, Encoding.UTF8, "text/plain");
return resp;
}
}
这是我的 JavaScript 代码:
$.ajax({
type: "GET",
url: "http://localhost:8080/api/Chat/HelloWorld",
cache: false,
contentType: "text/plain",
success: function (data) {
alert(data);
},
error: function (error) {
alert('error');
}
});
它总是显示“错误”。怎么了? 顺便说一句,当我复制浏览器地址栏中的 url 时,浏览器可以显示来自 web api 的正确消息。
【问题讨论】:
-
你调试代码了吗?是否到达控制器?
-
"It always shows 'error'. What's wrong?"- 好吧,“错误”显然不是一个非常有用的错误消息。服务器对 AJAX 调用的实际响应是什么?这可能包含更多有用的信息。另外,当你调试这个时,服务器端是否会抛出异常? -
在您的 javascript 代码中也使用
console.log,例如:console.log(error)以查看错误所在。 -
你得到什么错误?尝试使用 firebug 进行调试!看看你得到什么回应
-
尝试访问localhost:8080/api/Chat/HelloWorld url 时得到什么结果?