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.
[WebMe开发者_运维知识库thod]
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?
You can actually avoid the serialization and parsing by having your Page Method just return your object.
So, it would look like:
[WebMethod]
public static ViewModel GetTestData()
{
var viewModel = createOrGetMyViewModelObjectFromSomewhere();
return viewModel;
}
On the JavaScript side, it would look like:
$.ajax({
type: 'POST',
url: '/blah/default.aspx/GetTestData',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (output) {
var viewModel = output.d;
ko.applyBindings(viewModel);
}
});
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.
What if you remove the contentType param?
Hey try putting empty data parameter above dataType: 'json', like following
data: "{}",
dataType: 'json',
that will do a trick!!
I did not understand clearly. If you can't parse JSON string try this magic code:
var viewModel = eval('(' + data + ')');
where data
is your response from server.
精彩评论