PHP / Symfony - 如何将javascript变量传递给PHP脚本

PHP / Symfony  - 如何将javascript变量传递给PHP脚本

问题描述:

Following is my code snippet.

function funcUrl(){

    var element = 10; 

    '<a href="<?=url_for('@someurl?id=' + element)?>"

}

--please see the above javascript function. I am passing the javascript variable element in the PHP script of href. Howver it gives me error beacuse of element variable. If I just harcode the value instead of passing javascript varibal it works just fine. Can someone help me how to pass the javascript varibale correctly in the above script so taht I can pass the value of the parameter dynamically?

To pass a variable in a GET you should encode it. In PHP that is done with rawurlencode(). You can do the same thing in Javascript with encodeURIComponent().

You will then need to decode the value in your PHP script with rawurldecode().

try this

function funcUrl(){

    var element = 10; 

    '<a href="<?=url_for('@someurl?id='.'<script>'+element+'</script>')?>"></a>'

}