jquery - 使用JQuery解析XML,需要通过属性名查找

标签 jquery html xml

我正在尝试解析一些 XML 数据以在基本网页中显示。 XML 如下:

    <response> 
  <variable name = "Input1">False</variable> 
  <variable name = "Input2">False</variable> 
  <variable name = "Input3">False</variable> 
  <variable name = "Input4">False</variable> 
  <variable name = "Input5">False</variable> 
  <variable name = "Input6">False</variable> 
  <variable name = "Input7">False</variable> 
  <variable name = "Input8">False</variable> 
</response> 

我有一些显示的代码,但目前我在 1 个文本区域中显示了所有 8 个变量。

        $(document).ready(function()
        {
          $.ajax({
            type: "GET",
            //To change controller, please chnage the IP below.
            url: "http://172.20.2.17/query/variable?Input1&Input2&Input3&Input4&Input5&Input6&Input7&Input8",
            dataType: "xml",
            success: parseSystem

          });
        })      
        //Parse System XML Response 
        function parseSystem(xml)
{

  $(xml).find("response").each(function()
   {    

        $("#Input1").append($(this).find("variable").text())
    $("#Input2").append($(this).find("variable").text())
    $("#Input3").append($(this).find("variable").text())
    $("#Input4").append($(this).find("variable").text())
    $("#Input5").append($(this).find("variable").text())
    $("#Input6").append($(this).find("variable").text())
    $("#Input7").append($(this).find("variable").text())
    $("#Input8").append($(this).find("variable").text())
   });

我希望 XML 中的 Input1 链接到 HTML 中的 #Input1 等等。

感谢您抽出宝贵的时间,我们真的很感激。

最佳答案

$(xml).find("response").each(function()
   {    

    $("#Input1").append($(this).find("variable[name=Input1]").text())
    $("#Input2").append($(this).find("variable[name=Input2]").text())
    $("#Input3").append($(this).find("variable[name=Input3]").text())
    $("#Input4").append($(this).find("variable[name=Input4]").text())
    $("#Input5").append($(this).find("variable[name=Input5]").text())
    $("#Input6").append($(this).find("variable[name=Input6]").text())
    $("#Input7").append($(this).find("variable[name=Input7]").text())
    $("#Input8").append($(this).find("variable[name=Input8]").text())
   });

但是还有一个更灵活的功能:

$(xml).find("response").each(function(){
     $(this).find("variable").each(function(){
          var id = $(this).attr("name");
          $("#"+id).append($(this).text())
     });
});

关于jquery - 使用JQuery解析XML,需要通过属性名查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5259151/

相关文章:

javascript - JQuery 可编辑选择数据库中的数据

javascript - AJAX 请求太大?

javascript - 单击即可更改背景图像

javascript - 如何从 Kotlin 生成 HTML 标签?

c++ - XML 中的当前目录

javascript - 如何在网页中加载所有其他内容后最后显示图像

jQuery 滚动条间距问题

javascript - window.open 不打开窗口

php - 对 XML 使用 DOMDocument Validate() 会导致无限负载

c# - 在 C# 中测试某些东西是否是可解析的 XML