您不能提示用户从AJAX调用中下载文件。您可以做的一件事是,制作一个iframe,在其中放置一个表单,然后发布它。这样,它看起来就像一个AJAX调用,但是会提示用户下载文件。
// Create iframevar iframe = document.createElement('iframe');iframe.style.display = "none";document.body.appendChild(iframe);// Get the iframe's documentvar iframeDoc = iframe.contentdocument || iframe.contentWindow.document;// Make a formvar form = document.createElement('form');form.action = 'data/export.php'; // Your URLform.method = 'POST';// Add form element, to post your valuevar input = document.createElement('input');input.type = 'hidden';input.name = 'csvdata';input.value = gridCsvData; // Your POST data// Add input to formform.appendChild(input);// Add form to iframe// IE doesn't have the "body" property(iframeDoc.body || iframeDoc).appendChild(form);// Post the form :-)form.submit();PS您的PHP代码实际上并没有将CSV回显到屏幕上,只是将其保存到文件中。
标头调用后,请确保您具有:
readfile($myfile);



