Passing jQuery variable to PHP on the same page?

余生颓废 提交于 2020-01-07 17:44:50

问题


I know this is a frequent question on Stack Overflow but I couldn't find scenario where the PHP code is just above JS script in the same file. I guess ajax POST/GET won't do the job in this case?

(...)
var ww = $(window).width();
   </script>

<?php $ww = [data here] ?>

回答1:


You will have to use POST/GET to send a JS variable to PHP, because PHP is processed by the server and JS is processed by the client.

I know this isn't what you want to hear.




回答2:


This is the wrong approach. The PHP is all parsed / evaluated server side. Later, the users' browser gets to parse / evaluate the javascript. Even if the JS appears before the PHP in your file, the PHP is still evaluated server side before anything is passed to the browser. If you need client side values passed back to the server, you use AJAX for that. You can make decisions on the server side again, and in the response, trigger the JavaScript to take some action based on the decision the PHP made, but you don't get to mix / match client / server actions in a single file like this.




回答3:


I don't think there is any way, because javascript runs on your local machine AFTER PHP has been executed and has returned HTML/CSS/JS to your browser.




回答4:


I would use AJAX to pass what I need to the server to be processed, then based on the response, using Javascript, make any necessary adjustments. For example:

***PHP File***
<?php
$ww = $_POST['data'];
$result = doSomethingWithVariable($ww);
echo $result;

***HTML File***
<script>
...
var ww = $(window).width();
$.ajax({
    url: 'phpfile.php',
    type: 'POST',
    data: { data : ww },
    success: function (result) {
        doSomethingWithResult(result);
    }
});
</script> 



回答5:


What I did recently was passing a variable value to the attribute of an element that was dynamically generated by php. Then using the get attr() function of jquery to get the value. Worked perfectly!

PHP part:

foreach ((array)$photos['photos']['photo'] as $photo) {
$Maxcount++;
}

foreach ((array)$photos['photos']['photo'] as $photo) { 
echo "<img imgID='$IDcount' Maxcount='$Maxcount'

jQuery:

 var maxCount= $(".imageView").attr("maxCount");


来源:https://stackoverflow.com/questions/7680571/passing-jquery-variable-to-php-on-the-same-page

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