select onchange update php value


select onchange update php value

我想在不刷新页面的情况下用输入文本"连接"一个选择

这是我的示例

<select name="name_select" id="my_select">
  <option value="1">first</option>
  <option value="2">first</option>
  <option value="3">first</option>
</select>
<?php ...query(SELECT name FROM table WHERE id = value) ?>

然后在var$name中有来自db 的值

<input type="text" value="<?php echo $name; ?>" />

我想我必须使用jquerypost/get,但如何只更新我需要检查数据库的var?

就像Thamizhan在评论中说的那样,您需要使用AJAX。

这里有一个简单的例子:

HTML(index.HTML)

<select name="name_select" id="my_select">
  <option value="1">first</option>
  <option value="2">first</option>
  <option value="3">first</option>
</select>

JS

$('#my_select').on('change', function () {
    var selectData = $(this).val();
    $.ajax({
        type: "POST",
        url: "custom.php",
        data: {'selectData': selectData },
        success: function (json) {
            // do things
        }
    });
}

PHP(custom.PHP)

if (isset($_POST['selectData'])) {
    var_dump($_POST['selectData']); // $_POST['selectData'] is the selected value
    // query here
    // and you can return the result if you want to do some things cool ;)
}
$("#my_select").on("change", function () {
   $.ajax({
        url: "phpfile.php",
        method: 'POST',
        data: {val: $(this).val()},
        success: function (data) {
            $("[type='text']").val(data);
        }
    });
});

在phpfile.php 中

include("db.php");
// ... your code ...
// execute sql(SELECT name FROM table WHERE id = value) and return value.

请澄清一件事,为什么您需要在这里进行sql查询。

<option value="1">first</option>

第一个是名称,第1个是选项。然后我们可以在不使用sql和ajax的情况下将first或1放入输入框中。

仅对此使用jquery

$(document).ready(function(){
  $("#my_select").change(function(){
    var thisval = $(this).val();    
    $("input").val(thisval);
  });
});