【问题标题】:Submit with AJAX select values PHP使用 AJAX 提交选择值 PHP
【发布时间】:2017-06-08 15:24:33
【问题描述】:

我有此代码,但我无法在不刷新页面的情况下更改提交时的变量。你能帮我用 AJAX 做吗?

代码: ..................................................... ....................

<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>

【问题讨论】:

  • 尝试将你的 php 代码分离到另一个文件中,然后在其中调用 ajax

标签: php ajax forms


【解决方案1】:

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

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

	//post ajax jquery command
    $.post(<?php echo "'".$_SERVER['PHP_SELF']."'"; ?>, {
            device:device
    }, function(result){
            alert(result);
    });
	//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>

【讨论】:

  • 嗨,这行出现错误:var device = document.getElementById('device').value;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 2016-02-29
  • 2013-04-21
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
相关资源
最近更新 更多