XMLHttpRequest()并输出csv文件 [英] XMLHttpRequest() and outputting csv file

查看:432
本文介绍了XMLHttpRequest()并输出csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过向新窗口发出html表单POST来成功生成csv文件,并使用PHP来回复:

I can successfully generate a csv file by issuing an html form POST to a new window and use PHP to respond with:

header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="'.date("Ymdhis").'.csv"');
print get_lines();

然而,这会使窗口打开并留空。

However, this leaves the the window open and blank.

我要么自动关闭窗口(识别Content-Disposition),要么我宁愿完全忽略窗口,只需onClick,调用XMLHttpRequest()将表单变量发送给PHP,生成数据文件,然后提示用户保存或打开。

I want to either close the window automatically (on recognition of the Content-Disposition) or I would prefer to ignore the window completely and simply onClick, call XMLHttpRequest() send the form variables to the PHP, generate the data file and then prompt the user to save or open.

我试过:

var xhReq = new XMLHttpRequest();
var parameters = "";

for ( i=0; i<formObj.elements.length; i++ ) {
  parameters += formObj.elements[i].name + "=" + encodeURI( formObj.elements[i].value ) + "&";
}

xhReq.open("POST", outputLocation, false);
xhReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhReq.setRequestHeader("Content-length", parameters.length);
xhReq.setRequestHeader("Connection", "close");
xhReq.send(parameters);

document.write(xhReq.responseText);

但这不起作用,因为响应只是作为文本打印到屏幕上。

but this doesn't work because the response is simply printed as text to screen.

我真正想要的是,一旦我掌握了所有数据,就可以在不打开新窗口的情况下发出新的header()调用 - 这是否可以使用javascript?

What I really want, is once I have all the data, to issue a new header() call without opening a new window - is this possible using javascript?

推荐答案

您需要在新窗口中发送 POST 请求以便做这个。
我建议您创建一个隐藏表单并将其 target 属性设置为 _blank

You need to send the POST request in a new window in order to do this. I would suggest that you create a hidden form and set it's target attribute to _blank

您应该在服务器端设置 Content-disposition HTTP标头以强制下载。

You should set the Content-disposition HTTP header on the server-side to force a download.

您正在调用 document.write ,它将文本字符串转储到浏览器中,这可能不是您想要做的。

You are calling document.write, which dumps a text string into the browser, this is likely not what you wish to do.

这篇关于XMLHttpRequest()并输出csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆