php - 使用 php 和 jquery 将 xml 数据上传回服务器

标签 php jquery xml

我目前正在编写一个使用 xml 的应用程序。我使用这个访问 xml 文件 -

$.ajax({
    type: "GET",
    url: "data/data.xml",
    dataType: "xml",
    success: function (xml) {
        data = xml;
        init(); 
    }
});

然后,我使用 $(data).find 等更改数据中的一些元素,这似乎会更改值。

然后我需要做的是将这个变量“数据”上传回我的服务器并进行更改。我有这段代码可以将其发回 -

$.ajax({ 
    url: "saveXml.php", 
    type: "POST", 
    contentType: "text/xml", 
    processData: true, 
    data: data,
    success: function(){
        console.log('should have saved')
    } 
});

我的 php 脚本看起来像这样。

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

也许我遗漏了一些东西,也许我需要先对 xml 进行编码,但找不到这样的示例。然而,当它似乎加载时,我收到成功回调,但我的 xml 文件现在是空的。

最佳答案

不确定我完全明白你需要什么,但你应该这样做:

Ajax

     $.ajax({
        type: "GET",
        url: "data/data.xml",
        dataType: "xml",
        error:function(response){ 
        console.log(response);
         },
        success: function (xml) {

            init(xml); 
        }
    });

 function init(xml){
         $.ajax({ 
                url: "saveXml.php", 
                type: "POST", 
                contentType: "text/xml", 
                dataType:'xml',
                processData: true, 
                data: {'xml':xml},
                error:function(response){ 
                console.log(response);
                },
                success: function(data){
                    console.log(data); //check your console.log now
                } 
            });
    }

PHP

 <?php
    $xml = $_POST['xml'];
    //you don't need to open the file, you have the source of the file in $_POST['data']
    echo $xml;
    ?>

关于php - 使用 php 和 jquery 将 xml 数据上传回服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13525995/

相关文章:

php - 如何确保 Laravel Blade 中的唯一 ID?

php - 将数组值显示为数组中的数字

javascript - 在悬停时更改图像后将图像更改回原始图像?

xjb 绑定(bind)文件的 XML 命名空间问题

php - 在 PHP 中使用 Dom 对象,在某些节​​点中重新声明默认命名空间

php - Ubuntu 命令行报告 PHP 版本为 5.3.3 但 phpinfo 显示为 5.5.9

jquery - 如何设置$(this)指的是什么?

javascript - Powerange - 通过 javascript 更改值

html - 在 <span> 标签中嵌入 XSL 代码

php - 拉拉维尔。两个项目的公共(public)队列