PHP Javascript variable help

前端 未结 3 1228
傲寒
傲寒 2021-01-27 10:47

Is there any way to pass a javascript variable to a php function or simply assign a js variable to a php variable....???

test(\"asdas\"); I need to update \"asdas\" to a

相关标签:
3条回答
  • 2021-01-27 11:19

    You can pass value from js to PHP using ajax request or add js value to URL and then reload page.

    Variant #1 (using ajax):

    JS side (jquery)

    var js_var = 'hello';
    $.ajax({
       type: "POST",
       url: "some.php",
       data: "js_var="+js_var,
       success: function(msg){
         alert( "Data Saved: " + msg );
       }
     });
    

    PHP side

    $js_var = isset($_POST['js_var']) ? $_POST['js_var'] : '';

    Variant #2 (with page reload):

    JS side

    <script type="text/javascript">
    <!--
    var js_var = 'hello';
    window.location = "http://www.yoursite.com/?js_var="+js_var;
    //-->
    </script>
    

    PHP side

    $js_var = isset($_GET['js_var']) ? $_GET['js_var'] : '';

    0 讨论(0)
  • 2021-01-27 11:25

    When you want to send something from JS to PHP or from PHP to JS, use Ajax. If PHP already knows the value it wants to send to JS when it's delivering the page, you can also embed it in JS:

    <script>
      var name="$name";
    </script>
    

    Edit: As porneL said, you should not put data in the page that way without escaping it to avoid opening XSS holes.

    Oh, and if you use AJAX, also pay attention on not making ajax data text/html or so to avoid XSS, too.

    0 讨论(0)
  • 2021-01-27 11:34

    you can't

    0 讨论(0)
提交回复
热议问题