将JSON(从php)打印到ajax到bootstrap模式

时间:2015-04-16 21:34:11

标签: php mysql ajax json twitter-bootstrap

现在这个看起来有点复杂,也许我已经掌握了比我能管理更多的东西,但这似乎是我能达到我需要的唯一方式。

我是一个完全的新手,我正在盲目地为我正在进行的项目(这是整个项目中最复杂的事情),所以任何帮助都将非常感谢!

我基本上有一个bootstrap网页,这个网页显示一个用户列表(来自php的while循环)。我需要用户做的是从中选择一个用户并在bootstrap模式中编辑表单中的详细信息。

到目前为止,我已经完成了所有工作,模态加载等,并且来自各种来源的网络已经和JSon争吵,但我从来没有学过它,而且远远超出了我的深度。目前正在印刷' [对象HTMLCollection]'在每个领域。

首先,这是模态和版本的HTML。列表:

模态(完美出现)

<div class="modal fade" id="editUserModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
      <div class="modal-dialog">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h2 class="modal-title" id="editModalLabel"></h2>
          </div>
          <div class="modal-body">
            <form>
                <div class="form-group">
                    <label for="username" class="control-label">Username:</label>
                    <input type="text"  name="username" class="form-control" id="username"></input>
                </div>
                <div class="row">
                <div class="col-lg-12">
                    <div class="form-group">
                        <label for="password" class="control-label">Password:</label>
                            <div class="input-group">
                                <span class="input-group-btn">
                                <input type="button" class="form-control" value="Change Password" onClick="changeRandomPassword();">&nbsp;
                                </span>
                                <input type="text"  name="password" class="form-control" id="password" value="" required></input>
                            </div>
                    </div>
                </div> 
             </div> 
                <div class="form-group">
                    <label for="firstName" class="control-label">First Name:</label>
                    <input type="text" name="firstName" class="form-control" id="firstName">
                </div>
                <div class="form-group">
                    <label for="lastName" class="control-label">Surname:</label>
                    <input type="text" name="lastName"  class="form-control" id="lastName">
                </div>
                <div class="form-group">
                    <label for="jobTitle" class="control-label">Job Title:</label>
                    <input type="text" name="jobTitle"  class="form-control" id="jobTitle">
                </div>
                <div class="form-group">
                    <label for="TaskTeam" class="control-label">Task Team:</label>
                    <input type="text" name="TaskTeam"  class="form-control" id="TaskTeam">
                </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
            <button type="button" class="btn btn-success">Submit Changes</button>
          </div>
        </div>
      </div>
    </div>

这是php列表:(再次没有麻烦)

<?php 
include("dbconnect.php"); 

$dbQuery= mysql_query("SELECT * FROM users ORDER BY lastName ASC;"); 

while($dbRow = mysql_fetch_array($dbQuery))
{
$userID = $dbRow['id'];
$username = $dbRow['username'];
$firstName = $dbRow['firstName'];
$lastName = $dbRow['lastName'];
$jobTitle = $dbRow['jobTitle'];
$userteam = $dbRow['TaskTeam'];
$admin = $dbRow['admin'];

echo '<tr>';
echo '<td>';
echo '<button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModal" value='.$userID.' id="user" name="user"" data-user='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>';
echo '</td>';
echo '<td>'.$firstName.'</td>';
echo '<td>'.$lastName.'</td>';
echo '<td>'.$jobTitle.'</td>';
echo '<td>'.$userteam.'</td>';
echo '<td>'.$admin.'</td>';

echo '<td>';
echo '<a href="deleteUser.php?id='.$userID.'">';
echo '<button type="button" name="delete_row" id="delete_row" class="close">';
echo '<span title="Delete" aria-hidden="true" class="glyphicon glyphicon-trash">';
echo '</span>';
echo '<span class="sr-only">';
echo 'Delete';
echo '</span>';
echo '</button>';
echo '</a>';
echo '</td>';

echo '</tr>';
}

echo mysql_error();
mysql_close();

?>

这就是问题所在:

<script>
    $('#editUserModal').on('show.bs.modal', function (event) 
    {
        var button = $(event.relatedTarget)
        var recipient = button.data('user')
        var modal = $(this)
        modal.find('.modal-title').text('Edit ' + recipient + "'s details.")
        $(function () 
          {
            $.ajax(
            {  
                type: 'GET',
                url: "getUser.php?id=",             
                data: 'recipient',
                dataType: "json",
                success: function(data) 
                {
                    var obj = JSON.parse(data);
                    $.each(obj, function(key, val) 
                    {
                        console.log(val);           
                         var id = data[0];              
                         var firstName = data[1];       
                         var lastName = data[2];
                         var username = data[3];
                         var password = data[4];
                         var jobTitle = data[5];
                         var TaskTeam = data[6];
                         var admin = data[12];      
                    });
                }
            })
        })
        modal.find('.modal-body #firstName').val(firstName)
        modal.find('.modal-body #lastName').val(lastName)
        modal.find('.modal-body #username').val(username)
        modal.find('.modal-body #password').val(password)
        modal.find('.modal-body #jobTitle').val(jobTitle)
        modal.find('.modal-body #TaskTeam').val(TaskTeam)
    })
</script>

最后这里是php文件来获取用户的详细信息:(这也可以,但只能手动完成 - 这是大部分不包括密码等)

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$userid = intval($_GET['id']);
$sql="SELECT * FROM users WHERE id = $userid";
$result = $conn->query($sql);

/*
$user = array();
while ($row = mysql_fetch_array($result)) {
  $details = array(
    "username"          => $row['username'],
    "firstName"         => $row['firstName'],
    "lastName"          => $row['lastName'],
    "taskTeam"          => $row['taskTeam']
  );
  $user[] = $details;
}
echo json_encode($user);
$conn->close();
*/

if ($result->num_rows > 0) {
    // output data of each row
    $array = array();
    while($row = $result->fetch_assoc()) {
        array_push($array, $row);
    }
    echo json_encode($array);
} else {
    echo "0 results";
}
$conn->close();

很抱歉缺少Mysqli我知道这是最新的标准,目前正在该项目中实施。

任何帮助都会很棒!感谢

1 个答案:

答案 0 :(得分:1)

您的代码存在问题:

var obj = JSON.parse(data);
$.each(obj, function(key, val) 
{
    console.log(val);           
     var id = data[0];              
     var firstName = data[1];       
     var lastName = data[2];
     var username = data[3];
     var password = data[4];
     var jobTitle = data[5];
     var TaskTeam = data[6];
     var admin = data[12];      
});

您已经告诉过您的AJAX调用,您希望从PHP脚本返回JSON。您使用dataType: "json"执行此操作。所以这里没有理由这样做:var obj = JSON.parse(data);。既然你告诉你的AJAX调用你将收到JSON,它会在PHP脚本完成时自动解析它。

要访问数据,只需使用.语法即可。例如,data.firstName

此外,您可能需要在

中更改PHP文件中的此行
echo json_encode($array);

header('Content-Type: application/json');
echo json_encode($array);

此外,您的PHP脚本需要进行一些清理:

<?php 
include("dbconnect.php"); 

$dbQuery = mysql_query("SELECT * FROM users ORDER BY lastName ASC;"); 

while ($dbRow = mysql_fetch_array($dbQuery)) {

    $userID    = $dbRow['id'];
    $username  = $dbRow['username'];
    $firstName = $dbRow['firstName'];
    $lastName  = $dbRow['lastName'];
    $jobTitle  = $dbRow['jobTitle'];
    $userteam  = $dbRow['TaskTeam'];
    $admin     = $dbRow['admin'];

    echo '
    <tr>
        <td>
            <button type="button" class="btn btn-primary close" data-toggle="modal" data-target="#editUserModal" value='.$userID.' id="user" name="user"" data-user='.$userID.'><span title="Edit" aria-hidden="true" class="glyphicon glyphicon-edit"></span></button>
        </td>
        <td>'.$firstName.'</td>
        <td>'.$lastName.'</td>
        <td>'.$jobTitle.'</td>
        <td>'.$userteam.'</td>
        <td>'.$admin.'</td>
        <td>
            <a href="deleteUser.php?id='.$userID.'">
                <button type="button" name="delete_row" id="delete_row" class="close">
                    <span title="Delete" aria-hidden="true" class="glyphicon glyphicon-trash"></span>
                    <span class="sr-only">Delete</span>
                </button>
            </a>
        </td>
    </tr>';
}

echo mysql_error();
mysql_close();
?>