为什么javascript在php中将这些变量作为对象?

时间:2019-05-21 21:38:49

标签: javascript php html mysql

我试图将一些变量传递给PHP文件,以便运行SQL查询。但是JavaScript会将这些变量作为对象传递。为什么会这样呢?我该如何更改?

  <?php include 'dbconfig.php';?>
<?php header('Content-Type: text/html; charset=utf-8');?>

<!DOCTYPE HTML PUCLIC "-//W3C//DTDHTML 4.0 Transitional//EN">
<HTML>
<HEAD>
    <TITLE>LIBRARY DATABASE</TITLE>
    <link rel="stylesheet" type="text/css" href="mytable.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylesheet" type="text/css" href="jquerycss.css">
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
    <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js" type="text/javascript"></script>
    <script type="text/javascript">

        $(function () { 

            var new_dialog = function (type, row) {
            var dlg = $("#dialog-form").clone();
            var memberID = dlg.find(("#memberID")),
            MFirst = dlg.find(("#MFirst")),
            MLast = dlg.find(("#Mlast")),
            Street = dlg.find(("#Street")),
            number = dlg.find(("#number")),
            postalCode = dlg.find(("#postalCode")),
            Mbirthdate = dlg.find(("#Mbirthdate"));
                type = type || 'Create';
                var config = {
                    autoOpen: true,
                    height: 500,
                    width: 600,
                    modal: true,
                    buttons: {
                        "Create an account": save_data,
                        "Cancel": function () {
                            dlg.dialog("close");
                        }
                    },
                    close: function () {
                        dlg.remove();
                    }
                };
                if (type === 'Edit') {
                    config.title = "Edit User";
                    get_data();
                    delete (config.buttons['Create an account']);
                    config.buttons['Edit account'] = function () {
                        window.open("edituple.php?memberID="+ memberID +"&MFirst=" + MFirst +"&MLast=" + MLast +"&Street=" + Street
                        +"&number=" + number + "&postalCode=" + postalCode +"&Mbirthdate=" + Mbirthdate);
                        dlg.dialog("close");
                    }; 
                }
                dlg.dialog(config); 
                function get_data() {
                    var _memberID = $(row.children().get(1)).text(),
                     _MFirst = $(row.children().get(2)).text(),
                     _MLast = $(row.children().get(3)).text(),
                    _Street = $(row.children().get(4)).text(),
                    _number = $(row.children().get(5)).text(),
                    _postalCode = $(row.children().get(6)).text(),
                    _Mbirthdate = $(row.children().get(7)).text();
                    memberID.val(_memberID);
                    MFirst.val(_MFirst);
                    MLast.val(_MLast); 
                    Street.val(_Street);
                    number.val(_number); 
                    postalCode.val(_postalCode);
                    Mbirthdate.val(_Mbirthdate); 
                } 
                function save_data() {
                    $("#users tbody").append("<tr>" + "<td>" + (fname.find("option:selected").text() + ' ').concat(lname.find("option:selected").text()) + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "<td><a href='' class='edit'>Edit</a></td>" + "<td><span class='delete'><a href=''>Delete</a></span></td>" + "</tr>");
                    dlg.dialog("close");
                }
            }; 
            $(document).on('click', 'span.delete', function () {
                $(this).closest('tr').find('td').fadeOut(1000, 
        function () {
            // alert($(this).text());
            $(this).parents('tr:first').remove();
        }); 
                return false;
            });
            $(document).on('click', 'td a.edit', function () {
                new_dialog('Edit', $(this).parents('tr'));
                return false;
            }); 
            $("#create-user").button().click(new_dialog); 
        });
    </script>
</HEAD>
<BODY>
<div class="navbar">
                <a href="mydatabase.php">Home</a>
                <a href="member_table.php">Member</a>
                <a href="book_table.php">Book</a>
                <a href="borrows_table.php">Borrows</a>
              </div>
              <br><br>
              <div class="navbar2">
                    <a href="insert.php">Insert</a>
                    <a href="update.php">Update</a>
                    <a href="delete.php">Delete</a>
                  </div>

    <TABLE class="minimalistBlack">
        <thead>
        <tr>
        <th> memberID </th>
        <th> First Name </th>
        <th> Last Name </th>
        <th> Street </th>
        <th> Number </th>
        <th> Postal Code </th>
        <th> Birthdate </th>
        <th> Update </th>
        </tr>
        </thead>
        <?php 
            $conn= mysqli_connect("localhost","root","","library");
            mysqli_set_charset($conn, "utf8");

            if ($conn -> connect_error){
                die("Conenction failed:". $conn->connect_error);
            }
            $sql="SELECT memberID,MFirst,MLast,Street,number,postalCode,Mbirthdate FROM member";
            $result = $conn->query($sql);
            if ($result->num_rows>0){

                while($row= $result->fetch_assoc()){
                    echo "<tr>";
                    echo "<td>".$row['memberID']."</td>";
                    echo "<td>".$row['MFirst']."</td>";
                    echo "<td>".$row['MLast']."</td>";    
                    echo "<td>".$row['Street']."</td>"; 
                    echo "<td>".$row['number']."</td>"; 
                    echo "<td>".$row['postalCode']."</td>"; 
                    echo "<td>".$row['Mbirthdate']."</td>"; 
                    echo "<td><a class =\"edit\" href=\"\">Edit </a>
                     | <a href=\"deletefmtable.php?memberID=$row[memberID]\" onClick=\"return confirm('Are you sure you want to delete?')\">Delete</a></td>";  
                }
                echo "</TABLE>";
            }
            else { echo "0 result"; }
            $conn->close();
         ?>
    </TABLE>
    <div id="dialog-form" title="Create new user" style="display:none">

        <p class="validateTips">

            All form fields are required.</p>       

            <form>

        <fieldset>

            <label for="memberID">

                Member ID </label>

                <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />

            <label for="MFirst">

                First Name</label>

                <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />


            <label for="MLast">

                Last Name </label>

            <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />

            <label for="Street">

                Street </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

            <label for="number">

             number </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

            <label for="postalCode">

            Postal Code </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

            <label for="Mbirthdate">

            Birthdate </label>

            <input type="text" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

        </fieldset>

        </form>

    </div>
</BODY>
</HTML>

代码的目的是显示一个表并在侧面进行编辑和删除。删除按钮效果很好,但是对于编辑,我需要将上述变量传递给php文件

2 个答案:

答案 0 :(得分:1)

好的,我喜欢挑战。从顶部开始:

  1. 您要避免将PHP和HTML尽可能混合使用。 JavaScript也是如此。理想情况下,它们完全位于单独的文件中,但是我们将在这里将它们分开。在顶部做您的工作,并限制自己在下面仅显示代码。

  2. 始终转义数据以HTML格式显示。为此,请使用htmlspecialchars()

  3. 这不是1999年,您应该使用现代的文档类型声明。现代HTML还意味着小写的元素,并且不需要type元素上的<script>属性。

  4. 一致地缩进和间隔代码。它将帮助您调试问题并提高效率。

  5. 在使用变量之前或使用变量var时声明它们{

  6. 您不应该克隆此对话框。单击时只需用新值填充它。

  7. 在这里,我们开始探讨您的实际问题。首先,您过于依赖全局变量。举一个例子,您可以在get_data()函数中设置所有这些变量的值。但这是在设置对话框时发生的,而不是在按下按钮时发生的。这些东西需要在提交表单时发生。 (但请参阅#12。)

  8. 我们可以完全放弃该get_data()函数,并将其功能移至其所属的位置,即编辑链接的点击处理程序。

  9. 使用data-属性是将数据从PHP传递到客户端脚本的好方法。您可以在按钮上设置这些属性,并避免笨拙的DOM遍历,而只需使用$.data()

  10. 每当更改或创建某些内容时,请使用POST操作,而不要使用GET。顾名思义,GET仅用于获取资源,不应执行更改数据的操作。

  11. 为什么使用带有close属性的对话框将其完全删除?我假设您想重复使用它,否则您将不会在新窗口中弹出编辑结果。

  12. 如果您不使用Ajax,则根本不需要让JS参与表单提交。只需让表单正常提交即可。

  13. 与您的代码保持一致。为什么所有其他按钮都是单独的,删除按钮为何在HTML中具有事件处理程序?

  14. 您没有关闭<tr>元素,而是关闭了两次<table>元素。

  15. 所有表单元素的名称和ID错误。

这应该可以解决问题:

<?php
    include 'dbconfig.php';
    $conn= mysqli_connect("localhost","root","","library");
    mysqli_set_charset($conn, "utf8");

    if ($conn -> connect_error) {
        die("Conenction failed:". $conn->connect_error);
    }
    $sql="SELECT memberID, MFirst, MLast, Street, number, postalCode, Mbirthdate FROM member";
    $result = $conn->query($sql);
    $data = [];
    while ($row= $result->fetch_assoc()) {
        $data[] = array_map("htmlspecialchars", $row);
    }
    $conn->close();

    // test data
    $data = [
        ["memberID"=>1, "MFirst"=>"John", "MLast"=>"Smith", "Street"=>"Main St", "number"=>"123", "postalCode"=>"K1A 1A1", "Mbirthdate"=>"1990-06-27"]
    ];
    header('Content-Type: text/html;charset=utf-8');
?>
<!DOCTYPE html>
<html>
<head>
    <title>LIBRARY DATABASE</title>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <link rel="stylesheet" type="text/css" href="mytable.css">
    <link rel="stylesheet" type="text/css" href="styles.css">
    <link rel="stylesheet" type="text/css" href="jquerycss.css">
    <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

    <script>
        $(function () { 
            var new_dialog = function (type) {
                var dlg = $("#dialog-form");
                type = type || 'Create';
                var config = {
                    autoOpen: true,
                    height: 500,
                    width: 600,
                    modal: true,
                    buttons: {
                        "Create an account": function () {
                            $("#users tbody").append("<tr>" + "<td>" + (fname.find("option:selected").text() + ' ').concat(lname.find("option:selected").text()) + "</td>" + "<td>" + email.val() + "</td>" + "<td>" + password.val() + "</td>" + "<td><a href='' class='edit'>Edit</a></td>" + "<td><span class='delete'><a href=''>Delete</a></span></td>" + "</tr>");
                            dlg.dialog("close");
                        },
                        "Cancel": function () {
                            dlg.dialog("close");
                            return true;
                        }
                    }
                };
                if (type === 'Edit') {
                    config.title = "Edit User";
                    delete (config.buttons['Create an account']);
                    config.buttons['Edit account'] = function () {
                        // just let the form submit itself normally
                        $("#dialog-form form").submit();
                        dlg.dialog("close");
                    };
                }
                dlg.dialog(config); 
            }; 
            $(document).on('click', 'span.delete', function () {
                $(this).closest('tr').find('td').fadeOut(1000, function () {
                    $(this).parents('tr:first').remove();
                }); 
                return false;
            });
            $("a.edit").click(function () {
                // populate the values; we're getting all the info from
                // the data- attributes on the link itself
                // note JS makes them all lowercase
                $("#dialog-form input#memberID").val($(this).data("memberid"));
                $("#dialog-form input#MFirst").val($(this).data("mfirst"));
                $("#dialog-form input#MLast").val($(this).data("mlast"));
                $("#dialog-form input#Street").val($(this).data("street"));
                $("#dialog-form input#number").val($(this).data("number"));
                $("#dialog-form input#postalCode").val($(this).data("postalcode"));
                $("#dialog-form input#Mbirthdate").val($(this).data("mbirthdate"));
                new_dialog('Edit');
                return false;
            }); 
            $("a.delete").click(function() {
                return confirm('Are you sure you want to delete?');
            });
            $("#create-user").button().click(function() {
                // just clear the values
                $("#dialog-form input").val("");
                new_dialog();
            }); 
        });
    </script>
</head>
<body>
    <div class="navbar">
        <a href="mydatabase.php">Home</a>
        <a href="member_table.php">Member</a>
        <a href="book_table.php">Book</a>
        <a href="borrows_table.php">Borrows</a>
    </div>
    <br/><br/>
    <div class="navbar2">
        <a href="insert.php">Insert</a>
        <a href="update.php">Update</a>
        <a href="delete.php">Delete</a>
    </div>

    <table class="minimalistBlack">
        <thead>
            <tr>
                <th> memberID </th>
                <th> First Name </th>
                <th> Last Name </th>
                <th> Street </th>
                <th> Number </th>
                <th> Postal Code </th>
                <th> Birthdate </th>
                <th> Update </th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($data as $row):?>
            <tr>
                <td><?=$row['memberID']?></td>
                <td><?=$row['MFirst']?></td>
                <td><?=$row['MLast']?></td>
                <td><?=$row['Street']?></td>
                <td><?=$row['number']?></td>
                <td><?=$row['postalCode']?></td>
                <td><?=$row['Mbirthdate']?></td>
                <td>
                    <a
                        class ="edit"
                        href="#"
                        <?php foreach ($row as $k=>$v):?>
                        data-<?=$k?>="<?=$v?>"
                        <?php endforeach?>
                    >Edit</a> |
                    <a class="delete" href="deletefmtable.php?memberID=<?=$row['memberID']?>">Delete</a>
                </td>
            </tr>
        <?php endforeach;?>
        </tbody>
    </table>

    <div id="dialog-form" title="Create new user" style="display:none">
        <p class="validateTips">
            All form fields are required.</p>
            <form method="post" action="edituple.php" target="_blank">
                <fieldset>
                    <label for="memberID">Member ID </label>
                    <input type="text" name="memberID" id="memberID" value="" class="text ui-widget-content ui-corner-all" readonly="readonly" />

                    <label for="MFirst">First Name</label>
                    <input type="text" name="MFirst" id="MFirst" value="" class="text ui-widget-content ui-corner-all" />

                    <label for="MLast">Last Name </label>
                    <input type="text" name="MLast" id="MLast" value="" class="text ui-widget-content ui-corner-all" />

                    <label for="Street">Street </label>
                    <input type="text" name="Street" id="Street" value="" class="text ui-widget-content ui-corner-all" />

                    <label for="number">number </label>
                    <input type="text" name="number" id="number" value="" class="text ui-widget-content ui-corner-all" />

                    <label for="postalCode">Postal Code </label>
                    <input type="text" name="postalCode" id="postalCode" value="" class="text ui-widget-content ui-corner-all" />

                    <label for="Mbirthdate">Birthdate </label>
                    <input type="text" name="Mbirthdate" id="Mbirthdate" value="" class="text ui-widget-content ui-corner-all" />
                </fieldset>
        </form>
    </div>

</body>
</html>

您需要做的就是允许edituple.php而不是$_POST来查看$_GET。并且不要忘记使用准备好的语句进行数据库更新!我强烈建议使用PDO或更高级别的数据库API。 mysqli非常冗长,它确实旨在构建数据库API,而不是直接使用。

答案 1 :(得分:-1)

在发送之前使用JavaScript的JSON.stringify(your_variable)函数,在PHP端,使用json_decode($ _ GET ['data'])

your_variable应该是一个对象,不应将其包装为类似代码。做这样的事情:

data = {
    var _memberID = $(row.children().get(1)).text(),
     _MFirst = $(row.children().get(2)).text(),
     _MLast = $(row.children().get(3)).text(),
    _Street = $(row.children().get(4)).text(),
    _number = $(row.children().get(5)).text(),
    _postalCode = $(row.children().get(6)).text(),
    _Mbirthdate = $(row.children().get(7)).text();
    memberID.val(_memberID);
    MFirst.val(_MFirst);
    MLast.val(_MLast); 
    Street.val(_Street);
    number.val(_number); 
    postalCode.val(_postalCode);
    Mbirthdate.val(_Mbirthdate); 
}

然后通过ajax发布将此数据(字符串化的字符串或标头设置为内容类型:application / json)传递给php,在php端json_decode我上面提到的发布的数据,您将拥有一个数据数组在sql查询中。