问题
I have a web service that contains one method:
[WebMethod]
public string Movies()
{
using (var dataContext = new MovieCollectionDataContext())
{
var query = dataContext.Movies.Select(m =>new{m.Title,m.ReleaseDate}).Take(20);
var serializer = new JavaScriptSerializer();
return serializer.Serialize(query);
}
}
The method properly serializes the object, but when I view the response in FireBug, it looks like this:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"Title":"SQL","ReleaseDate":"\/Date(1224007200000)\/"},{"Title":"Termonator Salvation","ReleaseDate":"\/Date(1224007200000)\/"}]</string>
Here is jQuery method in which I use Kendo Data Source
$(function () {
alert("Welcome To Kendo");
var dataSource = new kendo.data.DataSource(
{
transport: {
read: {
type: "POST",
dataType: "json",
url: "/MovieService.asmx/Movies"
// contentType: "application/json; charset=utf-8"
}
},
change: function (e) {
alert(e);
},
error: function (e) {
alert(e[2]);
},
pageSize: 10,
schema: {
data: "d"
}
});
$("#MovieGridView").kendoGrid({
dataSource: dataSource,
height: 250,
scrollable: true,
sortable: true,
pageable: true,
columns: [
{ field: "Title", title: "Movie Name" },
{ field: "ReleaseDate", title: "Movie Release" }
],
editable: "popup",
toolbar: ["create"]
});
});
The above code show what I am doing in jQuery and when the error event call I got this error
SyntaxError: JSON.parse: unexpected character
How can I convert the above data into JSON so I can use it in jQuery? And where am I going wrong?
回答1:
You need to specify the ResponseFormat of the method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMovies() {
}
Note: For the sake of others who arrive at this question with similar issues, it's also important to note that you should being using POST
requests, not GET
requests. See: JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
EDIT
Based on the jQuery that you posted, you're not calling the correct method. You C# defines a method called GetMovies
, yet your jQuery is attempting to call a method called `Movies'.
This:
url: "/MovieService.asmx/Movies"
Should change to this:
url: "/MovieService.asmx/GetMovies"
来源:https://stackoverflow.com/questions/9914782/asmx-webservice-return-json-instead-of-xml