Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - Pass PHP variable within echo <script> content

I am trying to pass $php_variable to JavaScript content in echo tag in one php file. It is because I hope to append the query value from old_page_url to new_page_url by using window.location.

For example,

http://example/?data=1234 to http://example/something-else/1234

My code snippet:

<?php

$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + $php_variable";
echo "</script>";

I have tried:

<?php

$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + json_decode($php_variable)";
echo "</script>";

and

<?php

$php_variable = "testing";
echo "<script>";
echo "var toURL = 'http://example.com/something-else/'";
echo "window.location = toURL + <?php echo $php_variable; ?>";
echo "</script>";

But these two don't work. Any idea?

Update: Final Code Snippet

<?php

$php_variable = "testing";
$toURL = "http://example.com/something-else";
echo "<script>";
echo "window.location = '$toURL/$php_variable'";
echo "</script>";
question from:https://stackoverflow.com/questions/65713228/pass-php-variable-within-echo-script-content

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
echo "window.location = 'http://example.com/something-else/$php_variable'";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...