简体   繁体   中英

PHP headers inside of a javascript condition?

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");
    ?>
}

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM