【发布时间】:2015-06-09 04:03:14
【问题描述】:
我有一个 JSON 字符串,我在触发按钮时通过 Ajax 调用传递。 我希望能够做和理解的第一件事是将变量传回生成的文件而不将其保存到服务器。
这里发生的奇怪的事情是,变量值是由回调函数检索并由alert(data)调用显示的, 而 POST 变量被识别为空并且 JS 脚本将我带到一个空白的 process-data.php 页面。
当取消 empty() 条件时,我仍然可以正确显示变量 但是我没有空白页,而是下载了一个 0 字节的文件。
这可能是服务器问题,我正在运行 MAMP?
感谢您的回答。
这是 HTML 代码
<button onclick="aCall()" button type="submit" formmethod="post"> DL "x" value as text </button>
Ajax 代码:
function aCall(){
$.ajax({
url: 'process-data.php',
type: 'POST',
data: {'value': [{x:250,y:300}]}, //that's an example
success: function(data){
alert(data);
window.location = 'process-data.php';
}
});
}
这是 PHP 代码:
<?php
if (!empty($_POST['value'])) //I get a blank page with that condition on and a file if off.
{
$filename = 'test.txt';
header("Content-Description: File Transfer");
header("Content-Length: ". filesize("$filename").";");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/octet-stream; ");
header("Content-Transfer-Encoding: binary");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');
header('Pragma: public');
echo $_POST['value'][0]['x'];
exit;
}
?>
简而言之,这就是我得到的。
HTML -> AJAX -> PHP -> echo myValue
|
|
empty file <----------|
or Blank page |
|
popup |
showing the <---------'
variable's
value
【问题讨论】:
-
“发生的奇怪的事情......” 为什么要在回调之后谈论POST变量?发生了什么奇怪的部分?
-
我已经编辑了我的帖子。发生的情况是可以通过回调检索我想要的值,但我的文件是空的。
-
你确定你可以用
echo代替readfile()吗?您可能还想检查Content-Length:标头。 -
好吧,如果我放一个像 echo "exString" 这样的普通字符串,它会返回一个包含该字符串的文件。如果我输入 echo "exString".myValue."otherString",同样的事情,我会在我的文件中得到 "exStringotherString",在我的弹出窗口中得到 "exString250otherString"。
-
echo $_POST['value'] 在页面上弹出一个“NULL”返回我的 json 字符串
标签: javascript php jquery ajax download