簡體   English   中英

使用javascript動態添加數據庫時,如何使用php將信息添加到數據庫?

[英]how can i add info to a DB with php when its being dynamically added with javascript?

我有一個頁面,當我按下添加按鈕時,會使用javascript動態添加復選框,但是在將復選框每次添加到頁面時,我都希望將其保存到數據庫中。 我只是不確定如何去做,也許是ajax和php? 我知道如何使其插入只是讓它在每個添加上調用函數的問題。

javascript

$(document).ready(function() {
$('#btnSave').click(function() {
    addCheckbox($('#txtName').val());
     txtName.value="";
});

$("#remove").click(removeCheckbox);
$("#save").click(myFunction);
});

function addCheckbox(name) {
 var container = $('#cblist');
 var inputs = container.find('input');
 var id = inputs.length+1;

  $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
 $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
 $('<br/>').appendTo(container)
}

html / php

    $username = "root";
    $password = "";
   $hostname = "localhost"; 
     $database = "mydb";

     $conn = mysqli_connect($hostname, $username, $password, $database);
       ?>

       <div id="cblist">

       </div>
     <input type="button" value="Add Checkbox" id="btnSave" />

嘗試這種方式:

JScript(jQuery)

<script type="text/javascript">
    function addCheckbox(name) {
        var container = $('#cblist');
        var inputs = container.find('input');
        var id = inputs.length+1;

        $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
        $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
        $('<br/>').appendTo(container);

        //some changes - start
        var newCheckBox = '<input type="checkbox" id="cb' + id + '">';

        $.ajax({
            url: '/test.php',
            type: 'POST',
            data:{
                newCheckBox:newCheckBox
            },
            success: function(){
                alert('Ok');
            }
        });
        //some changes - end

    }


    $(function(){
        $('#btnSave').click(function() {
            addCheckbox($('#txtName').val());
             txtName.value="";
        });

        $("#remove").click(removeCheckbox);
        $("#save").click(myFunction);
    });
</script>

test.php

header('Content-type: text/html; charset=utf-8');

$newCheckBox = $_POST['newCheckBox'];

/*
 * here's your server-side code.
 */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM