簡體   English   中英

如何在 php 中使用 javascript 代碼?

[英]How can I use javascript code with php?

我在做什么?

我有一個dynamically created html division其中包含用戶可以在社交媒體上分享的用戶玩游戲的分數。

為了分享,我有元標簽,例如 facebook

<meta property="og:image" content= "<?php echo $img_url; ?>"/>

其中$img_urldynamically created html division截圖的鏈接。

test.php——我上面提到的元標記所在的位置,如果未設置$img_url ,我想截取html div屏幕截圖。

 <?php session_start(); $img_url = $_POST['img_url']; if(!isset($url)) { /* <script> function capture() { html2canvas will give var img. Which will be POSTED to testsave.php to save it in the server. } </script> */ } ?> <html> <!--dynamically created html division --> </html>

testsave.php -- 它將從test.php獲取發布的值並將屏幕截圖圖像保存到服務器,並將$img_url發送回test.php

 <?php session_start(); /*Get the base-64 string from data Decode the string Save the image function predefined for random string*/ $img_url = $random_str.".png"; file_put_contents($img_url, $unencodedData); $_SESSION['img_url'] = $img_url ; ?>

我的問題是什么?

當 facebook 抓取特定頁面時,它不會從其他頁面獲取session values或任何值。 所以我不能將img_val從 testsave.php 發送到另一個頁面,因為刮板不會讀取POSTED值。

所以,我在做什么是當刮板刮test.php然后如果$img_val沒有設置我希望我的代碼截取屏幕截圖並將js變量var imgtestsave.php以保存圖像,然后將回發$img_valtest.php值。

我知道上面的代碼可能有很多錯誤,比如我不能把js放在php 但是我嘗試了很多方法,但無法弄清楚。

您能否建議我該怎么做才能使代碼正常工作,或者您可以建議任何其他方法嗎?

你必須從 PHP 中回顯 HTML

<?php
  session_start();

  $img_url = $_POST['img_url'];

  if(!isset($url)) {

   echo "<script>
    function capture() {    

     //your js code here

     }
   </script>";  
 }
?>
<html>

<!--dynamically created html division -->

</html>

解決方案之一是使用 here-document 將整個 HTML 頁面分配給 PHP 變量,然后在符合您需要的地方回顯/打印它,您也可以在那里包含 Javascript 代碼

示例“此示例不包含您提到的圖像內容,但您可以使用任何 Javascript 代碼”

<?php

$variable=<<<_END
<html>
<p>Some HTML line...</p> 
<script>
//you can write the Javascript codes you need here
 console.log('Find this sentence at console !')
</script>
</html>
_END;

echo $variable;

?>

為了在瀏覽器中傳遞它,我們必須將 JS 代碼構造為 PHP 代碼中的字符串

例如。 Test.phtml - 我在某些條件下調用 js 函數。

<body>
 <?php if($this->emptyData){ ?>
    <div id="someTestDialog">
        <!-- call js function below -->
        <?php
            echo '<script type="text/javascript">testDialog();</script>';
        ?>
    </div>
<?php } ?>

</body>
<script>
function testDialog() {
    return $("<div class='dialog' title='Alert'><p>Hello World</p></div>")
        .dialog({
            resizable: false,
            height:90,
            width:90,
            modal: true,
            dialogClass: 'no-close success-dialog',
            buttons: {
                "OK": function() {
                $( this ).dialog( "close" );
            }
         }
    });}
$(document).ready(function() {
    var text = "some code here" });    </script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM