2014-03-27 54 views
0

我使用PHP代碼訪問了包含product_name,price和id到php變量的MySQL數據庫值。現在我想讓該變量持有MySQL數據以保存在Java Script變量中,以便我可以執行某些功能。如何在使用PHP訪問的JavaScript中存儲MySQL數據庫值

下面是代碼:

這是一個PHP文件:

<?php include("connect.php"); 

$plan = mysql_query("select id,price,product_name from product"); 
<select name='pro2' id='pro2' >\\dropdown menu for selecting product name 
<option>Select product</option> 
<?php while($proname2 = mysql_fetch_array($plan)) 
{ ?> 
<option value="<?php echo $proname2['product_name']; ?>" > 
<?php echo$proname2['product_name']; ?> </option> 
<?php } ?> 
</select> 
Unit Price:<input type="text" id="mytext1" name="mytext1" readonly="enabled" value=""/> 

<?php 
    $plan = mysql_query("select price,product_name from product"); 
    while($row = mysql_fetch_array($plan)) 
    { $r1=$row['product_name']; 
    $r2=$row['price']; 
     $user_data = array('product_nam' => '$r1', 'price' => '$r2'); 
?> 
<script type="text/javascript">\\ used java script to change the value of mytext to \\price which is selected by product name 
    alert(user_data.price); 
    var mytextbox2 = document.getElementById('mytext1'); 
    var mydropdown2 = document.getElementById('pro2'); 
    var user_data = <?php echo json_encode($user_data); ?>; 
    mydropdown2.onchange = function(){ 
     // test.value =this.value; 
     if(user_data.product_nam==this.value) 
     {    
      mytextbox2.value=user_data.price; 
     } 
     //to appened 
     //mytextbox.innerHTML = this.value; 
    } 
</script> 
    <?php } ?> 
+0

只要你可以這樣做<?php echo「」; ?> – Moussawi7

回答

0

對於一個新的一頁負載(未AJAX),作爲PHP代碼的數據之前,將執行被髮送到用戶,您可以直接將PHP變量值回顯到Javascript變量聲明中。

例如,嘗試:

 <script> 
      $(document).ready(function() { 
       var echome = <?php echo "1";?>; 
       console.log(echome); 
      }); 
     </script> 

另外,你應該避免使用mysql_〜函數調用。他們已被棄用。你應該考慮升級到mysqli或PDO。

相關問題