drodsh7940
2014-07-01 04:03
浏览 301
已采纳

我们如何在php变量中调用js或jq的变量?

can javascript or jquery variable can be read by php code?

Example

<script>
   var num = 3;
</script>
<php?
   $a = 20;
   $b = num*$a;
?>

anyone?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doukan4795 2014-07-01 04:13
    已采纳

    Short answer - No it can't. But there is an alternative known as AJAX where you can send a javascript variable to a php page and make it accessible to that page. Consider the following example:

    $.ajax({
       url:'some-php-page.php',
       type:'post',
       data:{num:3},
       success:function(data_returned)
       {
          // do anything you want with the data returned back
          alert(data_returned); // will alert 60
       }
    });
    

    some-php-page.php

    $num = $_POST['num']; // the key used in the "data" attribute of the ajax call
    $a = 20;
    $b = $num*$a;
    echo $b;
    

    Of course you'll need to include jQuery library in order to use the $.ajax({}). This can be done through plain javascript too, but I prefer to use jQuery as it is much simpler.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douchuang1852 2014-07-01 04:08

    PHP is interpreted on the server. Javascript is interpreted in the browser. Since PHP cannot run after the HTTP request has been fulfilled and a response has been sent to the browser, it is not possible for PHP to access a javascript variable.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题