我想做的事情肯定可以完成,但我做错了:我想在使用 Ajax 调用时创建一个 XML 文件。我得到了以下代码(合成的)。也许这个例子不起作用,只是为了举例说明:
HTML
<html>
<head>
<!-- JQuery 1.7 included -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<p>Create XML on server!</p>
<form id="prog" method="POST">
<input type="text" id="test" />
<button id="submit" type="submit"> Create now! </button>
</form>
<script>
jQuery.noConflict();
jQuery(document).ready(function($){
var test = $('#test').val();
// When the button it's clicked:
$('#submit').click(function () {
$.ajax({
// Este es el archivo PHP que procesa la información y envía el mail
url: "createXML.php",
type: "POST",
data: test,
success: function (html) {
// If succeed
if (html==1) {
alert("DONE!!");
}
}
});
});
// With this I cancel the default behaviour of the button so it doesn't submit by itself.
return false;
});
</script>
</body>
</html>
服务器中的PHP
<?php
echo "HI! Ajax arrived here and this code it's being executed!";
//I load a string to be the contents of the XML file
$exemel = simplexml_load_string('<example><simple>As simple as this!</simple></example>');
// I save the file as following:
$exemel->asXml('xml/DONE.xml');
echo 1;
?>
在此示例中,PHP 代码按原样工作,而另一个则不然。但在我的代码的整个上下文中,Ajax 调用是有效的,我毫不怀疑,因为它执行了它必须执行的所有其他操作,而只是创建 XML 代码没有执行。具有与此处完全相同的 PHP 代码,如果我执行 Ajax 调用,则不会创建该文件。如果在控制台中我会这样做
php createXML.php
XML 文件已成功创建。所以这不是 PHP 代码,同时它也不是我的 Ajax 调用中的错误,因为它做了它应该做的一切。可能会发生什么?
在我的真实代码中,在服务器的 PHP 文件中我这样做:
$test = (isset($_GET['test'])) ? $_GET['test'] : null;
//If something fails, I add the error to an errors array:
$errors = array();
isset($errors);
if (!$test) $errors[count($errors)] = 'Something failed with the test!';
//If there are any errors
if (!$errors) {
createXML ();
}
createXML() 函数包含我以前的代码。
试试这个
$xml = simplexml_load_string($_POST['test']);
if(file_put_contents("xmlfile.xml",$xml->asXML())){
echo "xml file created successfully";
}else{
echo "failed to create file";
}
同样在 php 端,你没有对 $_POST['test'] 做任何事情? xml 字符串在哪里..