【问题标题】:JQuery: How to get a simple string from ASP.NET WebAPI using AJAX?JQuery:如何使用 AJAX 从 ASP.NET WebAPI 获取简单字符串?
【发布时间】: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 时得到什么结果?

标签: jquery asp.net-web-api


【解决方案1】:

终于解决了。是因为跨域。

解决方案:在WebAPI控制器的响应头中添加“Access-Control-Allow-Origin: *”。

[HttpGet]
    public HttpResponseMessage HelloWorld()
    {
        string result = "Hello world! Time is: " + DateTime.Now + "";
        var resp = new HttpResponseMessage(HttpStatusCode.OK);

        // add this line to allow cross domain
        resp.Headers.Add("Access-Control-Allow-Origin", "*");

        resp.Content = new StringContent(result, Encoding.UTF8, "text/plain");
        return resp;
    }

详情请看以下帖子:

ajax problem - 200 OK in firebug but red message with no response body

jQuery AJAX cross domain

【讨论】:

    【解决方案2】:

    尝试使用以下代码在控制台中记录错误:

    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr.statusText); 
    }
    

    如果您无法让错误日志记录正常工作,请参阅 here

    【讨论】:

    • 它输出一个字符串'error'。会不会是跨域问题?
    • 如果它是一个跨域问题,它应该给你的不仅仅是“错误”,你会得到类似 NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http... '
    猜你喜欢
    • 2018-12-24
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 2015-03-14
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多