ASMX web服务 - 返回JSON而不是XML [英] ASMX webservice - return JSON instead of XML
问题描述
我有一个包含一个方法的Web服务:
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);
}
}
该方法正确序列化对象,但是当我查看在Firebug的响应,它看起来是这样的:
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>
下面是我用剑道数据源
$(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"]
});
});
上面的代码显示我在做什么在jQuery和当错误事件调用我得到这个错误
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
我怎么能转换成以上数据为JSON,所以我可以在jQuery中使用它?而我要去哪里错了?
How can I convert the above data into JSON so I can use it in jQuery? And where am I going wrong?
推荐答案
您需要指定的 ResponseFormat
方法:
You need to specify the ResponseFormat
of the method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMovies() {
}
注意:为他人着想谁在这个问题到达类似的问题,这也是必须注意的是,你应该使用 POST
的要求,而不是 GET
请求之中。请参阅:的 JSON劫持和ASP.NET AJAX 1.0如何避免这些攻击
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
修改
根据你贴出来,你不调用正确的方法jQuery的。你C#定义一个名为方法 GetMovies
,但您的jQuery试图调用一个叫做'电影'的方法。
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'.
这样的:
url: "/MovieService.asmx/Movies"
应该改成这样:
url: "/MovieService.asmx/GetMovies"
这篇关于ASMX web服务 - 返回JSON而不是XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!