我已验证来自C#Webmethod的JSON响应,所以我不认为这是问题所在。无法获取jQuery Ajax来解析JSON webservice结果
我试图解析结果使用简单的jQuery $ .ajax,但无论出于何种原因,我无法得到该方法正确地触发和解析结果,也偶然似乎无法得到函数来触发结果。他们对可以返回的JSON对象的大小有任何限制。
我也从一个“的Site.Master”页面中删除了此代码,因为它总是会刷新时,我打了简单的按钮。标签是否正确地使用jQuery元素,比如我从DOM抓取的按钮输入?
function ajax() {
//var myData = { qtype: "ProductName", query: "xbox" };
var myData = { "request": { qtype: "ProductName", query: "xbox"} };
$.ajax({
type: "POST",
url: "/webservice/WebService.asmx/updateProductsList",
data: {InputData:$.toJSON(myData)},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// var msg = {__type: "Testportal.outputData", id: "li1234", message: "it's work!", myInt:101}
alert("message=" + msg.d.ProductName + ", id=" + msg.d.Brand);
},
error: function (res, status) {
if (status === "error") {
// errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
var errorMessage = $.parseJSON(res.responseText);
alert(errorMessage.Message);
}
}
});
}
和页面:
<asp:Button ID="Button1" runat="server" OnClientClick="ajax();" Text="Button" />
而且Serverside集团WEBMETHOD:
public class WebService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public OutputData updateProductsList(InputData request)
{
OutputData result = new OutputData();
var db = new App_Data.eCostDataContext();
var q = from c in db.eCosts
select c;
if (!string.IsNullOrEmpty(request.qtype) && !string.IsNullOrEmpty(request.query))
{
q = q.Like(request.qtype, request.query);
}
//q = q.Skip((page - 1) * rp).Take(rp);
result.products = q.ToList();
searchObject search = new searchObject();
foreach (App_Data.eCost product in result.products)
{
/* create new item list */
searchResult elements = new searchResult()
{
id = product.ProductID,
elements = GetPropertyList(product)
};
search.items.Add(elements);
}
return result;
}
和辅助类:
public class OutputData
{
public string id { get; set; }
public List<App_Data.eCost> products { get; set; }
}
public class InputData
{
public string qtype { get; set; }
public string query { get; set; }
}
只是一个注意:尝试包装qtype和查询单引号。即“{'qtype':'”+ qtype +“','query':'”+ query +“'}”; – Marko 2010-07-06 19:52:54
谢谢!这是否,没有新的结果 - 也更新了$ .ajax方法。 – 2010-07-06 20:34:50
单引号的使用对于JSON不正确(请参阅http://www.json.org/或在http://www.jsonlint.com/上验证您的JSON数据) – Oleg 2010-07-06 23:01:58