【问题标题】:How to read XML data returned by webservice in JQuery如何在 JQuery 中读取 webservice 返回的 XML 数据
【发布时间】:2011-02-28 07:56:17
【问题描述】:

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 id=@id";
            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 中读取电机和 id_model 的值。但它要么返回对象(如果我仅引用 XML)或未指定或为空。

如何跟踪/调试从 .ASMX 文件返回的内容?

【问题讨论】:

    标签: jquery xml ajax web-services


    【解决方案1】:

    我没有复制粘贴你的代码,所以它有点不同,但你会明白的......

      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 中节点的名称(您在响应中获得)w 您想要获得的值

    【讨论】:

    • "xmlNode" 是一个特殊的标签?还是我把我的节点名放在那里?
    • 你把你的节点名放在那里:)
    【解决方案2】:

    你可以尝试用JSON代替xml

    【讨论】:

    • 但我想返回值而不是在 .ASMX 文件中生成整个 HTML 代码。
    • 你不需要在 asmx 中生成整个 HTML 代码。只需从 web 服务返回 json 而不是 xml。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-08-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多