gpt4 book ai didi

c# - 为什么 jQuery 不能管理这个 JSON?

转载 作者:行者123 更新时间:2023-11-30 12:09:35 24 4
gpt4 key购买 nike

我有一个返回此 json 的 C# 网络服务:

{"data":"2"}

是的。如果我从浏览器加载链接,我可以看到这个输出。方法是:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void IsFacebookPageLiked()
{
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(new { data = "2" }));
}

我用 jQuery 调用它:

$.ajax({
type: "POST",
url: myUrl,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log("success: " + data);
},
error: function (jqxhr, text, error) {
console.log("fail: " + error);
}
});

但结果总是:

fail: (an empty string)

代码有什么问题?为什么会引发异常?

最佳答案

这不是 jQuery 的错。必须有服务器端错误。否则 jQuery 不会进入 error 回调。

你怎么能确定这不是客户端错误

  • 检查您的网络流量(使用流量监视器、 Firebug 或浏览器的 native 开发工具)。也许您可以找到您的回复的提示(例如,在状态中)。也许您的请求没有按预期发送。
  • 检查回调函数的响应参数(文本和错误)。

可能的解决方案

我会试一试:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void IsFacebookPageLiked()
{
SimpleMessage message = new SimpleMessage() {Message = "Hello World"};
string json = JsonConvert.Serialize(message);
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.Write(json);
}

关于c# - 为什么 jQuery 不能管理这个 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21261724/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com