【发布时间】:2010-07-06 19:48:42
【问题描述】:
我已经验证了我的 C# Web 方法的 JSON 响应,所以我认为这不是问题所在。
我正在尝试使用简单的 jQuery $.ajax 解析结果,但无论出于何种原因,我都无法获得正确触发和解析结果的方法,顺便说一句,似乎也无法获得触发结果的函数。他们对可以返回的 JSON 对象的大小是否有任何限制。
我还从“Site.Master”页面中删除了这段代码,因为当我点击简单按钮时它总是会刷新。标签是否与我从 DOM 中获取的按钮输入等 jQuery 元素一起正常工作?
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" />
以及服务器端 Web 方法:
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 + "'}";
-
谢谢!这样做了,但没有新结果——还更新了 $.ajax 方法。
-
对 JSON 的单引号使用不正确(请参阅 json.org 或在 jsonlint.com 中验证您的 JSON 数据)