我已驗證來自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