2010-07-06 42 views
3

我已驗證來自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; } 
} 
+0

只是一個注意:嘗試包裝qtype和查詢單引號。即「{'qtype':'」+ qtype +「','query':'」+ query +「'}」; – Marko 2010-07-06 19:52:54

+0

謝謝!這是否,沒有新的結果 - 也更新了$ .ajax方法。 – 2010-07-06 20:34:50

+0

單引號的使用對於JSON不正確(請參閱http://www.json.org/或在http://www.jsonlint.com/上驗證您的JSON數據) – Oleg 2010-07-06 23:01:58

回答

1

的一個問題是,你沒有做任何事情來阻止提交表單,並在同一時間執行完全回發/重裝你開始你的$。阿賈克斯()回調的按鈕。

我建議佈線這件事悄悄地而不是使用OnClientClick屬性,像這樣:

$(document).ready(function() { 
    // May need to use $('<%= Button1.ClientID %>') if your Button is 
    // inside a naming container, such as a master page. 
    $('#Button1').click(function(evt) { 
    // This stops the form submission. 
    evt.preventDefault(); 

    $.ajax({ 
     // Your $.ajax() code here. 
    }); 
    }); 
}); 

我也奧列格同意,你應該使用json2.js爲您的JSON字符串化和解析。在較新的瀏覽器中,這將回退到瀏覽器的這些方法的本地實現,這會更快並且使分析更安全。

更新:

爲了回答您的有關數據,不,這看起來不正確的問題。

要最終發送到服務器這是什麼(沒有格式化):

{"request":{"gtype":"ProductName","query":"xbox"}} 

爲了實現這個目標,你想是這樣的:

var req = { request : { qtype: "ProductName", query: "xbox" }}; 

$.ajax({ 
    data: JSON.stringify(req), 
    // Remaining $.ajax() parameters 
}); 

記住requestqtypequery必須與您的服務器端結構匹配,並區分大小寫。

您也可以在定義請求對象(我喜歡,就個人而言,讓事情變得清晰可讀)更詳細:

var req = { }; 

req.request = { }; 

req.request.qtype = "ProductName"; 
req.request.query = "xbox"; 

我寫了一個多一點關於這個在這裏,如果你'重新感興趣:http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/

+0

謝謝!我也只是將JS取代爲注意到的一些錯別字。 我的數據看起來像是格式正確的Web方法!是的,我想知道這個完整的帖子。 – 2010-07-07 22:13:23

+0

thansk Dave-我真的很少使用Javascript,並沒有用它來做任何事情,就像以前一樣消化WS,所以這很有趣,但也有點乏味!我真的很感謝你花時間 – 2010-07-08 01:08:26

+0

謝謝戴夫,我其實有Firebug,因爲我沒有得到太多新信息而放棄使用它,但我確實使用了手表和斷點。 我實際上有最初的想法讓我的UpdatePanels落後於你的網站:http://encosia.com 它似乎現在工作,我只需要解析JSON響應並將其放置在HTML中,所以我仍在閱讀。 – 2010-07-08 01:38:24

1

你的服務器端代碼方法是什麼樣的?設置一箇中斷點。它被擊中了嗎?

它應該是這個樣子:

[WebMethod, ScriptMethod] 
public string updateProductsList(string qtype, string query) 
{ // stuff 
} 

而且,你的JavaScript數據PARAMS看起來不正確格式化。

+0

謝謝,我只是將該方法添加到帖子中。另外,當做jS params。我已經成功地使用這種格式從輸入框來回傳遞一個簡單的字符串,所以我決定不改變什麼工作! (至少爲此)。我試試這個新格式。 – 2010-07-06 20:28:20

1

在我看來,你的問題是你嘗試使用手動JSON序列化。有更直接的方法。您應該聲明[ScriptMethod (ResponseFormat = ResponseFormat.Json)][ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)],並直接返回對象而不是web方法中的字符串。在客戶端(在JavaScript)我嚴格推薦您使用JSON.stringify(從中可以從http://www.json.org/js.html下載json2.js)爲jQuery.ajaxdata參數的構建。

看看Can I return JSON from an .asmx Web Service if the ContentType is not JSON?How do I build a JSON object to send to an AJAX WebService?也可能在JQuery ajax call to httpget webmethod (c#) not working你有更多的實驗興趣。你可能有

+0

感謝Oleg,我將添加「ScriptMethod」(以前我曾經這樣做過,但是由於我使用的是手動序列化,所以無法正確設置),我喜歡你給我提供的關於轉換服務的文章到「WFC Restful」服務是個不錯的主意。如果我有好運氣,我會用我的結果回答這個問題。 – 2010-07-07 15:11:26

+0

歡迎您!我想聽聽我的其他答案對你也有幫助。謝謝。祝你好運,並在軟件開發方面取得很大成功! – Oleg 2010-07-07 15:25:45

+0

謝謝,我根據自己的閱讀做了一些更改,但尚未能夠正確格式化對象以發送到服務 - 我仍在玩它,我看到我需要給出輸入類型webservice在我的JSON字符串輸入 - 但我不斷收到:錯誤:對象不支持此屬性或方法 – 2010-07-07 21:30:47