对 ASP .NET 网站的 jQuery JSON 调用在 IE 中成功,但在 Firefox 或 Chrome 中失败
我使用以下 jQuery 从 ASP .NET 网站获取 JSON:
$.ajax({
type: 'POST',
url: '/blah/default.aspx/GetTestData',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(output) {
var viewModel = $.parseJSON(output.d);
ko.applyBindings(viewModel);
}
});
然后使用 Knockout 库来更新我的 UI。 default.aspx中获取数据的服务器端代码如下。
[WebMethod]
public static string GetTestData()
{
var viewModel = null; // Get viewModel data from elsewhere.
return new JavaScriptSerializer().Serialize(viewModel);
}
这在 IE 中工作正常,但当我在 Chrome 和 Firefox 中尝试时,JSON 不会返回。我的断点服务器端确实被击中,因此正在调用 Web 方法,但当它返回到浏览器时发生了一些事情。
我认为这可能与在浏览器或网络服务器端设置内容或 MIME 类型有关,但我还没有任何运气,有人有任何建议吗?
I'm fetching JSON from my ASP .NET website using the following jQuery:
$.ajax({
type: 'POST',
url: '/blah/default.aspx/GetTestData',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(output) {
var viewModel = $.parseJSON(output.d);
ko.applyBindings(viewModel);
}
});
And then using the Knockout library to update my UI. The server-side code in default.aspx to get the data is as follows.
[WebMethod]
public static string GetTestData()
{
var viewModel = null; // Get viewModel data from elsewhere.
return new JavaScriptSerializer().Serialize(viewModel);
}
This works fine in IE but when I try in Chrome and Firefox the JSON does not get returned. My breakpoint server-side does get hit so the web method is being called, but something is happening when it comes back to the browser.
I think it might be related to setting content or MIME types at either the browser or webserver end but I've not had any luck yet, does anyone have any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
实际上,您可以通过让页面方法返回对象来避免序列化和解析。
因此,它看起来像:
在 JavaScript 端,它看起来像:
因此,您不需要在 .NET 中序列化它,也不需要在客户端解析它。这一切都由两侧的“管道”处理。此外,传递
data: "{}"
也很重要(或者如果您需要参数,它们会放在这里)。另外,如果您调用的是 Web 服务而不是页面方法,那么您需要使用
[ScriptService]
属性来修饰该类。You can actually avoid the serialization and parsing by having your Page Method just return your object.
So, it would look like:
On the JavaScript side, it would look like:
So, you don't need to serialize it in .NET and you don't need to parse it on the client-side. It is all handled by the "plumbing" on both sides. Also, passing
data: "{}"
is important (or if you need parameters, they would go here).Also, if you were calling a web service instead of Page Method, then you need to decorate the class with a
[ScriptService]
attribute.如果删除 contentType 参数会怎样?
What if you remove the contentType param?
嘿,尝试将空的 data 参数放在 dataType: 'json' 上方,
就像下面
这样会有一个技巧!
Hey try putting empty data parameter above dataType: 'json',
like following
that will do a trick!!
我没听清楚。如果您无法解析 JSON 字符串,请尝试以下神奇代码:
其中
data
是来自服务器的响应。I did not understand clearly. If you can't parse JSON string try this magic code:
where
data
is your response from server.