【发布时间】:2014-01-18 01:06:33
【问题描述】:
我从服务器端的文件中获取了 xml 数据,无需使用服务器端脚本即可成功访问(例如,没有 php)。
我想在一些小的更改后将该 xml 数据写回服务器端的文件,同样不使用服务器端脚本(例如,没有 php)。这是我目前所拥有的:
<button id='WriteToXml'>Write to XML</button>
<script>
$('#WriteToXml').click(function () {
var output_xml;
$.ajax({
type: "GET",
url: "/data/testdata_input.xml",
dataType: "xml",
async: false,
success: function(xml) {
$(xml).find('input').remove();
$(xml).find('test').append('<output></output>');
output_xml = xml;
}
});
// Alternative code?
// $.post( "/data/testdata_output.xml", $(output_xml), "xml" );
$.ajax({
type: 'POST',
url: "/data/testdata_output.xml", //url of receiver file on server
data: $(output_xml) , //your data
contentType: "text/xml",
dataType: "xml",
cache: false,
async: false,
success: function(xml) {console.log( 'success\n'+ $(xml).find('test') );}
});
});
</script>
在another SO thread 中,我读到由于javascript 的设计(出于安全原因),必须使用服务器端脚本。但是后来in another thread,我看到了不涉及php的代码,所以我希望我可以使用该代码写入服务器上的xml文件:
$.ajax({
type: 'POST',
url: "/data/testdata_output.xml", //url of receiver file on server
data: "<test></test>" , //your data
contentType: "text/xml",
dataType: "xml",
cache: false,
async: false,
success: function(xml) {console.log( 'success\n'+ $(xml).find('test')
到目前为止,我收到一条成功消息,但服务器上的 xml 文件保持不变。很高兴了解我误解的地方。同时,我将在服务器端使用这个 php 代码并尝试让它工作:
//javascript
$.post('savedata.php', {data: "<test></test>",filename: "/data/testdata_output.xml"}, function(){/*Save complete*/});
//savedata.php
$data = $_POST['data'];
$filename = $_POST['filename'];
$f = fopen($filename, 'w+');
fwrite($f, $data);
fclose($f);
不过还是能理解就好了。
另外,我喜欢在 $.post 代码中使用 xml 文件类型而不是 php 文件(基于 $.post jquery doc)的一些说明:
$.post( "/data/testdata_output.xml", "<test></test>", "xml" );
谢谢
【问题讨论】:
-
我不相信没有某种服务器端表单/ajax 处理程序就可以进行服务器端工作。允许这种注入将是一个严重的安全漏洞。
标签: javascript php xml jquery