PHP headers inside of a javascript condition?

ε祈祈猫儿з 提交于 2020-01-06 02:11:31

问题


I'd like to send headers with PHP, inside of a javascript condition. Is that possible?

if ($('body').hasClass('browserChrome')) {
    <?php
       header("Content-Type: application/x-chrome-extension");
       header('Content-Disposition: attachment; filename="http://example.com/file.crx"');
       header("Pragma: no-cache");
       header("Expires: 0");
    ?>
}

回答1:


That won't work. First, your web server will execute the PHP script, resulting in an HTML page with JavaScript. That is then sent to the user's web client, which will display the HTML and execute the JavaScript. There is no trace of the PHP code by the time the JavaScript interpreter gets to it.




回答2:


No, it is not possible. (Well, more like, it's not meaningful or useful, and will likely cause page errors.)

The php code runs on your server before the page is sent out, like a baby in a stork bill, on its way to the client browser. The stork flies for a long time, through good weather and bad, storms, ice, snow, hunting parties, and pollution. At long last, the stork reaches your customer as they wait patiently for their new baby web page to appear.

Then, suddenly, -~ p00f ~- and the page arrives. At this point, the JavaScript in the page runs.




回答3:


if you need send some headers from JS(only), you can use method setRequestHeader of object XMLHttpRequest

new XMLHttpRequest(); 
//or 
new ActiveXObject(...) for IE
...
xmlHttp.open(... 
xmlHttp.setRequestHeader("Cache-Control", "no-cache, must-revalidate");  
xmlHttp.setRequestHeader("Pragma", "no-cache"); 

or can use some method JS frameworks (jQuery, Prototype, etc,)

But as has already been answered, is not correct write php code in js




回答4:


It seems as if you are trying to download a file through javascript, more like, push the file to the client browser. However, as it has been answered, its not possible for the code to work, as it happens on the server, and js runs on the client.

To achieve that, you would need to use javascript itself, ajax in this case, to download the relevant content.

You may find how to download file from javascript here : http://www.codeproject.com/KB/scripting/FileDownloadUsingJScript.aspx



来源:https://stackoverflow.com/questions/5022701/php-headers-inside-of-a-javascript-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!