我在使用jQuery / AJAX提交表单时遇到麻烦,并返回成功消息+ XML文件(在PHP中生成)。
这就是我现在所拥有的:
invoice.php
:
<form method="post" id="invoiceform">
<? /* Populate the form with input later on. For now, the XML data is hardcoded in PHP */ ?>
<button type="submit">Submit form</button>
</form>
//Submit the form:
$('#invoiceform').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
e.stopImmediatePropagation(); //prevent double.
//Show the loading message.
$form = $(this);
// Use Ajax to submit form data
$.ajax({
url: '/api/invoice/invoice_converter',
type: 'POST',
data: $form.serialize(),
dataType: "json",
success: function(data) {
console.log(data);
if (data.result == 'success') {
//Success
$(".status").html(data.message);
} else {
$(".status").html(data.message);
}
},
error: function(data) {
console.log("Something went wrong!");
console.log(data);
}
});
return false;
});
好的,上面只是将表单提交到下面的页面
invoice_converter.php
:
$invoice = new Invoice;
if($_POST)
{
$convertInvoice = $invoice->convertInvoice();
if($convertInvoice == 1){
$error = "Error: Error message goes here.";
$stop = true;
}
if($stop){
$result = array("result" => "error","message" => $error);
}else{
$result = array("result" => "success","message" => $convertInvoice);
}
}
header('Content-type: application/json');
echo json_encode($result);
因此,上面的页面处理返回消息。实际的XML生成函数位于页面
下面 functions.php
:
function convertInvoice(){
/* create a dom document with encoding utf8 */
$domtree = new DOMDocument('1.0', 'UTF-8');
/* create the root element of the xml tree */
$xmlRoot = $domtree->createElement("xml");
/* append it to the document created */
$xmlRoot = $domtree->appendChild($xmlRoot);
$currentTrack = $domtree->createElement("track");
$currentTrack = $xmlRoot->appendChild($currentTrack);
/* you should enclose the following two lines in a cicle */
$currentTrack->appendChild($domtree->createElement('charge','letter'));
$currentTrack->appendChild($domtree->createElement('description','Payable cover letters'));
$currentTrack->appendChild($domtree->createElement('charge','vat'));
$currentTrack->appendChild($domtree->createElement('description','Payable VAT'));
/* get the xml printed */
$xml = $domtree->saveXML();
return $xml;
}
在console.log中从上面返回的数据是:
<?xml version="1.0" encoding="UTF-8"?>
<xml>
<track>
<charge>letter</ charge >
<description>Payable cover letters</ description >
<charge>vat</ charge >
<description>Payable VAT</ description >
</track>
</xml>
这是正确的,但是,我希望能够&#34;保存&#34;以上在XML文件中,并使其可供用户下载。
答案 0 :(得分:1)
您需要创建一个可写文件并将 $ xml 写入文件。
此代码创建 track.xml ,并将下载链接插入文档。
<?php
$file = fopen('track.xml', 'w+'); //Create file
fwrite($file, $xml); //Write xml to file
fclose($file); //Close file
echo '<a href="track.xml">Download</a>'; //Make download link
?>
注意:track.xml必须是可写的。您可以通过执行:
使其可写chmod 755 track.xml