2011-02-28 121 views
1

ASMX返回XML數據:如何讀取Web服務在JQuery中

public class ItemRecord 
    { 
     public string model { get;set; } 
     public string verzia { get;set; } 
     public string typ { get;set; } 
     public string motor { get;set; } 
    } 

    [WebMethod] 
    public ItemRecord GetRecord(int id) 
    { 
     ItemRecord record = new ItemRecord(); 

     using (SqlConnection sConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["bazarovkyConnectionString"].ToString())) 
     { 
      sConnection.Open(); 


      SqlCommand sCommand = sConnection.CreateCommand(); 
      sCommand.CommandText = "select id_model, motor from data_motorizacia where [email protected]"; 
      sCommand.Parameters.AddWithValue("@id", id); 

      SqlDataReader sReader = sCommand.ExecuteReader(); 
      if (sReader.Read()) 
      { 
       record.model = sReader["id_model"].ToString(); 
       record.motor = sReader["motor"].ToString(); 
      } 
     } 

     return record; 

    } 

JQUERY:

id = $("#view_id", row).text(); 

$.ajax({ 
    type: "POST", 
    url: "/data.asmx/GetRecord", 
    data: "{'id':'" + id + "'}", 
    contentType: "application/json; charset=utf-8", 
    dataType: "xml", 
    processData: false, 
    error: function (XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); }, 
    success: function (xml) { ajaxFinish(xml); } 
}); 

function ajaxFinish(xml) { 
    // parse the object 
    alert($(xml).find("motor").text()); 

} 

我想要做的是讀電機和id_model在ajaxFinish的價值。但是它要麼返回對象(如果我只指向XML)或者未指定或空的。

如何跟蹤/調試.ASMX文件返回的內容?

回答

1

你可以嘗試使用JSON而不是XML

+0

但我想返回值,而不是在.ASMX文件中生成完整的HTML代碼。 – feronovak 2011-02-28 08:16:56

+0

您不需要在asmx中生成完整的HTML代碼。只需從webservice返回json而不是xml。 – 2011-02-28 08:18:27

2

我沒有複製粘貼你的代碼,所以它的有點不同,但你會得到的想法......

var arr= new Array(); 
    var loopCounter = 0; 

$.ajax({ 
      type: "POST", 
      url: "yourURL", 
      dataType: "xml", 
      success: function(xml) { 
       $(xml).find('xmlNode').each(function() { 
        arr[loopCounter] = $(this).find('xmlNode').text(); 
        loopCounter += 1; 
       }); 

這裏ARR是在其中讀取值的數組,並使用loopCounter將數據存儲在數組arr中,xmlNode是xml中的節點名稱(您將得到的響應)wwhose您想要的值

+0

「xmlNode」是一個特殊的標籤嗎?或者我把我的節點名稱? – 2013-06-19 07:51:19

+0

你把你的節點名稱:) – Rafay 2013-06-19 17:36:10