一千萬個為什麽

搜索

如何在JQuery中讀取webservice返回的XML數據

ASMX:

    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());

}

我想要做的是在ajaxFinish中讀取motor和id_model的值。但它要麽返回對象(如果我只引用XML),要麽返回未指定或空。

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

最佳答案

我沒有復制粘貼你的代碼,所以它有點不同但你會明白...

  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中的節點名稱(你得到的響應)你想得到的值

轉載註明原文: 如何在JQuery中讀取webservice返回的XML數據