我希望能够从我的服务器加载xml文件。使用jQuery编辑xml中的节点,然后使用php将此更改与xml文件的其余部分一起保存回服务器。有人知道怎么做吗?我有更改xml节点的代码,可以在我的控制台中看到它。但无法将代码恢复到我的服务器。
谢谢!
<?php
$xml = $_POST['xml'];
$file = fopen("data.xml","w");
fwrite($file, $xml);
fclose($file);
?>
$.post('saveXml.php', { xml: $(data)}, function(data){alert('data loaded');});
如果我是console.log(数据)我得到#document和所有xml节点。我也在我的服务器上获取了data.xml文件,但它是空白的。
答案 0 :(得分:4)
之前从未这样做,但在此处找到了一些信息:Convert xml to string with jQuery
我测试了以下内容,它将修改原始xml并作为$_POST['xml']
收到的字符串发送回服务器
$(function() {
$.get('test.xml', function(xml) {
var $xml = $(xml)
/* change all the author names in original xml*/
$xml.find('author').each(function() {
$(this).text('New Author Name');
})
var xmlString=jQ_xmlDocToString($xml)
/* send modified xml string to server*/
$.post('updatexml.php', {xml:xmlString },function (response){
console.log(response)
/* using text dataType to avoid serializing xml returned from `echo $_post['xml'];` in php*/
}'text')
}, 'xml')
});
function jQ_xmlDocToString($xml) {
/* unwrap xml document from jQuery*/
var doc = $xml[0];
var string;
/* for IE*/
if(window.ActiveXObject) {
string = doc.xml;
}
// code for Mozilla, Firefox, Opera, etc.
else {
string = (new XMLSerializer()).serializeToString(doc);
}
return string;
}