transfer a Variable from php to js

前端 未结 3 1701
野的像风
野的像风 2020-12-22 07:32

I got really confused when i tried to transfer variables from php to js. everything is fine when i try to get value using an id
for example:

var name = $         


        
3条回答
  •  孤城傲影
    2020-12-22 08:15

    You have to generate syntactically VALID javascript. PHP can echo text into ANY part of the page it's generating, but that doesn't necessarily mean it's actually USABLE text. In your case, you've forgotten a ;, so your generated javascript is actually a syntax error:

    var num = ;
                                   ^--- missing
    

    The same sort of thing occurs when you're outputting text. Consider where you're storing someone's name into a variable:

    
    
    

    This LOOKS ok, but it'll actually generate yet another syntax error:

        var name = Miles O'Brien;
    

    there's no quotes around the whole string, and the embedded quote will START a string in javascript, leading the JS interpreter to complain about an undefined variable "Miles", an undfined variable "O", and an unterminated string literal.

    Instead, the PHP should have been:

     var name = ;
    

    The JSON encapsulation guarantees that you're embedding syntactically valid Javascript values.

提交回复
热议问题