【问题标题】:How to change the value of an xml node with jquery?如何使用 jquery 更改 xml 节点的值?
【发布时间】:2011-01-12 09:24:33
【问题描述】:

这可能是一个简单的问题,但不知道该怎么做。 我想加载和修改一个xml文件,然后通过php保存xml。

代码如下:

 $.ajax({
  type: "GET",
  url: "menu.xml",
  dataType: "xml",
  success: function(xml) {
   $(xml).find('menu_item').each(function(){
    //change the value of menu_item
    $(this).empty();
    $(this).text($("textarea").attr("value"));
    //send xml to php
    $.post('save_xml.php', $(xml), function(data){alert("Data Loaded: " + data);});
   }

  }
 });

下面是 save_xml.php 的样子:

<?php

    $xml = $GLOBALS["HTTP_RAW_POST_DATA"];
    $file = fopen("file.xml","w");
    fwrite($file, $xml);
    fclose($file);
    echo "ok";

?> 

【问题讨论】:

    标签: jquery xml ajax


    【解决方案1】:

    这是你要找的吗?

    $(this) 是您使用.each() 迭代的每个menu_items

    你的代码变成了

    $(xml).find('menu_item').each(function(){
       $(this).text("New Value");
    });
    

    希望对你有帮助

    编辑

    要将其发布回服务器,我会这样做:

    $.post('save_xml.php', { xml: $(xml)}, function(data){alert("Data Loaded: " + data);});
    

    然后在 PHP 文件中

    <?php
      $xml = $_POST['xml'];
      $file = fopen("file.xml","w");
      fwrite($file, $xml);
      fclose($file);
      echo "ok";
    ?> 
    

    此代码未经测试,可能有多种原因无法运行,文件的写入权限等。

    【讨论】:

    • 谢谢,你很有帮助!现在我如何使用 jquery 将此 xml 发送到 php?我有一个将 xml 写入服务器的 save_xml.php。
    • @iulian 很高兴我能帮上忙。请随时接受我的回答。要将 XML 传递回 PHP,您需要 jQuery.post() api.jquery.com/jQuery.post 其中 data 是您要编写的 XML。
    • 我想是的,为了清楚起见,用第二部分编辑你的问题,我会修改我的答案。这样您就可以清楚地插入代码。
    • 谢谢,我把修改。我希望你能帮助我。
    • @iulian 我已经修改了您要发回 php 文件的数据元素
    猜你喜欢
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2017-03-10
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多