2017-01-24 41 views
-2

我有這段代碼,但無法刷新頁面時無法更改提交的變量。你能幫我用AJAX做到嗎?使用AJAX選擇值提交PHP

代碼: ............................................ .....................................

<form name="devices" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
    <select name="device" id="device"> 

     <option value="i1">i1</option> 
     <option value="i2">i2</option> 
    </select> 

</form> 

<?php 

$device = ""; 
if(isset($_POST['device'])) { 
$device = $_POST['device']; 

} 

switch ($device) { 

    case 'i1': 
    $w = 50; 
    break; 
    case 'i2': 
    $w = 100; 

    break; 
    default: 
    $w = 50;   
     break; 
} 

?> 
<div style="width: <?=$w?>px; height: 100px;background-color: black;"></div> 
+0

嘗試在另一個文件中分離您的php代碼,然後調用它ajax –

回答

0

<script src="jquery-3.1.1.min.js" type="text/javascript"></script> 
 

 
<script type="text/javascript" src="javascript.js"> 
 
\t //get value of the select box 
 
    var device = document.getElementById('device').value; 
 

 
\t //post ajax jquery command 
 
    $.post(<?php echo "'".$_SERVER['PHP_SELF']."'"; ?>, { 
 
      device:device 
 
    }, function(result){ 
 
      alert(result); 
 
    }); 
 
\t //it will send post data by post method 
 
</script>
Please Download the jquery file and put beside the php file 
 

 
<a href="https://jquery.com/">https://jquery.com/</a> 
 

 

 
<form name="devices" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> 
 
    <select name="device" id="device"> 
 

 
     <option value="i1">i1</option> 
 
     <option value="i2">i2</option> 
 
    </select> 
 

 
</form> 
 

 
<?php 
 

 
$device = ""; 
 
if(isset($_POST['device'])) { 
 
$device = $_POST['device']; 
 

 
} 
 

 
switch ($device) { 
 

 
    case 'i1': 
 
    $w = 50; 
 
    break; 
 
    case 'i2': 
 
    $w = 100; 
 

 
    break; 
 
    default: 
 
    $w = 50;   
 
     break; 
 
} 
 

 
?> 
 
<div style="width: <?=$w?>px; height: 100px;background-color: black;"></div>

+1

嗨,它給這一行上的錯誤:var device = document.getElementById('device')。value; – Alvaro