【问题标题】:jquery post error when using .NET HttpListener使用 .NET HttpListener 时 jquery 发布错误
【发布时间】:2014-11-11 20:44:04
【问题描述】:

我在没有网络服务器的 html 页面上有 javascript (file://)。在页面上我有执行此操作的 javascript

$.post("http://localhost:1234/", json_data ).fail(function(){alert('Fail');});

没有.fail,这工作得很好。我需要将数据发送到我的 .NET 应用程序。但是我想在由于某种原因失败时收到警报(比如忘记启动应用程序)。但是,当我添加 .fail 时,即使我的 .NET 代码看到推荐并按预期运行,我 100% 的时间都会得到它。下面是.NET 代码。为什么我会收到错误/失败?我尝试查看错误消息,它只是“错误”。我尝试在 firebug 中查看响应,但我看不到响应,尽管我可以看到响应长度和服务器(一些 MS/.NET 标头,如 MS HTTP API)

HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:9001/");
listener.Start();
//...
HttpListenerContext context = listener.GetContext();

HttpListenerRequest request = context.Request;
var data = new StreamReader(request.InputStream).ReadToEnd();
//...
HttpListenerResponse response = context.Response;

string responseString = @"{""command"":""Success""}";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);

response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);

【问题讨论】:

    标签: jquery .net


    【解决方案1】:

    如果没有失败函数,错误就会被忽略。

    问题是您不能发布到与用于加载 HTML 页面的域不同的域。这与same origin policy 冲突。

    使用file:// 从磁盘加载的文件与http://localhost:1234 的来源不同。您应该使用localhost 作为您的域来加载您的 HTML。

    【讨论】:

    • 是的,这行得通。我添加了这一行,它修复了所有问题context.Response.AddHeader("Access-Control-Allow-Origin", "*");
    • 酷,请注意,并非所有浏览器都支持此标头。 stackoverflow.com/questions/4403865/…
    猜你喜欢
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2011-05-21
    • 2018-12-23
    • 2011-08-05
    • 2019-01-01
    相关资源
    最近更新 更多