如何使用ajax发布选定的值

时间:2018-05-25 08:32:37

标签: javascript php jquery ajax

<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />

<script type="text/javascript">
  $(document).ready(function() {
    var selected_value = []; // initialize empty array 
    $(".source:checked").each(function(){
      selected_value.push($(this).val());
    });
    console.log(selected_value); //Press F12 to see all selected values
  });
</script>

我想提交此表单。在提交时,需要将所有选中的复选框值插入到数据库中的表中。我怎么能正确地做到这一点?

3 个答案:

答案 0 :(得分:0)

此代码很好解决您的问题:

<script type="text/javascript">
$(document).ready(function() {
    var selected_value = []; // initialize empty array 
    $(".source").change(function(){
        if( $( this ).is( ":checked" ) ){
            console.log($(this).val());
            selected_value.push($(this).val());
        }else{
            selected_value.splice(selected_value.indexOf($(this).val()), 1);
        }
        console.log(selected_value); //Press F12 to see all selected values
    });
});
</script>

答案 1 :(得分:0)

  • 首先在<form></form>
  • 中设置这些输入
  • 你的ajax电话在哪里?

在运行ajax调用之前,不要忘记包含ajax 把它添加到你的头上:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

这应该是你的ajax电话:

$.ajax({
   url: "your php url where it saves the values to the DB",
   data: {"selected values": selected_value},
   type: "POST",
   error:function(xhr){alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText); },
   success: function(data){ // do your things on succes }   
});`

每次选中/取消选中复选框时都应该更新数组。

<script type="text/javascript">
   $(document).ready(function() {
   var selected_value = []; // initialize empty array 
   $(".source").change(function(){
      if( $( this ).is( ":checked" ) ){
          selected_value.push($(this).val()); // add to array
       }else{
          selected_value.splice(selected_value.indexOf($(this).val()), 1); // find position and remove from array
       }
       console.log(selected_value); //Press F12 to see all selected values
    });
});
</script>

答案 2 :(得分:0)

您必须将复选框重命名为数组格式,因为它们已经具有相同的名称。

更改:

name="type"

name="type[]"

您可以使用jQuery serialize()将您的复选框数组转换为查询字符串,该字符串可用于将数据从ajax传输到PHP文件。

试试这段代码:

<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<form method="post" action="">
<input class="source" type="checkbox" name="type[]" value="4" />
<input class="source" type="checkbox" name="type[]" value="3" />
<input class="source" type="checkbox" name="type[]" value="1" />
<input class="source" type="checkbox" name="type[]" value="5" />
<input name="submit" value="submit" type="submit"/>
</form>
<script>
    $(document).ready(function(){
        $("input[name='submit']").click(function(e){
          e.preventDefault();
          $.ajax({
                url:'ajax-pdo-process.php', 
                method:'POST',
                data: $('input[name="type[]"]').serialize(),
                   success:function(data){
                       alert(data);
                   }
                });
            });
        });
</script>

要保存来自ajax的数据,可以在PHP文件中使用PDO。以下是您可以使用的模板。将其命名为ajax-pdo-process.php

<?php
    print_r($_POST);
    $db = new PDO('mysql:host=localhost;dbname=dbname', 'dbusername','dbpassword');
    $stmt = $db->prepare('INSERT INTO tbl(c0, c2) VALUES(:c0, :c1);');
    $stmt->bindValue(':c0', $_POST['type'][0]);
    $stmt->bindValue(':c1', $_POST['type'][1]);
    $stmt->execute();
?>

^我添加了print_r($_POST);,因此您知道哪些值正在发送给您的PHP处理程序。