使用jquery加载xml文件,对其进行编辑,然后使用php重新保存到服务器 [英] Use jquery to load xml file, edit it, then save to server again with php
问题描述
我希望能够从服务器加载xml文件.使用jQuery编辑xml中的节点,然后使用php将所做的更改与其余xml文件一起保存回服务器.有人知道怎么做吗?我有更改xml节点的代码,可以在控制台中看到它.但是无法将代码返回到我的服务器.
I want to be able to load an xml file from my server. Edit a node in the xml with jQuery and then save this change with the rest of the xml file back to the server using php. Anyone know how to do this? I have code that changes the xml node and can see this in my console. But cannot get the code back to my server.
谢谢!
<?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(data)我得到#document和所有xml节点.我还在服务器上获得了data.xml文件,但该文件为空.
if I console.log(data) I get #document and all the xml nodes. I also get the data.xml file on my server but it's blank.
推荐答案
Have never done this before but found some information here: Convert xml to string with jQuery
I have tested the following which will modify the original xml and send back to server as a string received by $_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;
}
演示: http://jsfiddle.net/54L5g/
这篇关于使用jquery加载xml文件,对其进行编辑,然后使用php重新保存到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!