PHP中ajax返回xml数据,PHP - 使用ajax提交表单,并返回XML

博客讲述了在前端使用jQuery/AJAX提交表单,后端用PHP处理并返回JSON结果的过程。PHP代码创建并返回XML数据,但目前只能在控制台显示,而非保存为文件供用户下载。作者寻求解决方案来实现XML文件的下载功能。
摘要由CSDN通过智能技术生成

我有麻烦提交我的表单使用jQuery / AJAX,并返回成功消息+ XML文件(在PHP中生成)。

这是我现在拥有的:

invoice.php:

/* Populate the form with input later on. For now, the XML data is hardcoded in PHP */ ?>

Submit 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中返回的数据是这样的:

letter charge >

Payable cover letters description >

vat charge >

Payable VAT description >

然而,这是正确的,我希望能够将上述内容“保存”在XML文件中,并使其可供用户下载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值