【问题标题】:How to jQuery an XML file over a PHP-script and parse it right?如何通过 PHP 脚本 jQuery 一个 XML 文件并正确解析它?
【发布时间】:2012-04-03 22:43:06
【问题描述】:

我已经尝试了几种方法让我的 xml 脚本在 java 中解析,但我无法弄清楚!

我有 2 个文件。 如果调用 mysql_get.php,它会返回一个 XML 脚本。 post_alert.html 通过 jQuery $.post(..) 从 mysql_get.php 获取 XML 脚本,如下所示:

function init2() {

    var response;
    $.post("mysql_get.php", function (data) {
        response = data;
        alert(response)
    });
    var xml;
    xml = $.parseXML(response);
    alert($(response).find("item").each(function () {
        $(this).attr("id")
    }));
}

点击一个调用 init2() 的按钮后,我得到了 xml 样式的响应消息,正如我在弹出的警报中看到的那样。

<?xml version="1.0" encoding="uft-8"?>
<root>
<collection collection="locationPoint">
    <item id="1">
        <latitude>23.4442</latitude>
        <longitude>51.2341</longitude>
    </item>

    <item id="2">
        <latitude>2849.24</latitude>
        <longitude>213.132</longitude>
    </item>
</collection>

但是警报没有弹出“1”,因为我希望正确解析。

我做错了什么?

【问题讨论】:

    标签: javascript jquery xml ajax parsing


    【解决方案1】:

    这里有几件事: 你的 xml 文件的第 1 行应该是 UTF-8 而不是 UFT-8 应该删除第 2 行,否则请确保您有一个结束标记,无效的 xml

    那么这里是一个小例子,希望对你有帮助:

    <html>
        <head>
            <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>
        </head>
        <body>
            <div id="dc"></div>
        </body>
        <script type="text/javascript">
            $(document).ready(function() {
                $.ajax({
                    url: 'mysql_get.php',
                    type: 'post',
                    dataType: 'xml',
                    success: function(data) {
                        $(data).find('item').each(function () {
                            $('#dc').append($(this).attr('id') + '<br/>')
                        });
                    },
                    error: function(data) {
                        $('#dc').html('error');
                    }
                });
            });
        </script>
    </html>
    

    【讨论】:

      【解决方案2】:

      AJAX 中的 A 代表异步。 $.post(..) 之后的代码在调用$.post 之后立即执行,而不管响应状态如何。

      您必须将var xml..-code 移入 $.post 调用。
      此外,.each() 仅循环遍历元素,而不返回 ID。使用 .map() 创建一个包含 id 的对象,使用 .toArray() 获取它的数组表示。

      function init2() {
          $.post("mysql_get.php", function(data) {
              var response = data;
              var xml = $($.parseXML(response));
              alert(response.find("item").map(function () {
                  return $(this).attr("id")
              }).toArray() );
          });
      }
      

      【讨论】:

        【解决方案3】:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-10-18
          • 2012-03-23
          • 1970-01-01
          • 2018-05-23
          • 2013-02-21
          • 2012-06-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多