如何在不刷新页面的情况下显示名称值而不是该值的ID(使用jQuery)

时间:2014-04-22 16:12:54

标签: php jquery ajax pdo

供参考,我使用的是mySQL数据库。这必须在没有页面刷新的情况下完成(因此需要使用AJAX完成[我正在使用jQuery来实现我的AJAX功能])。例如,有一个人有一个名字,姓氏,他们被分配到最少一个工作或最多2个工作。有2个表:

第一个表从作业表中获取id并将其用作外键。

表“tbl_person”:

+------+-------------+------------+--------+--------+
| p_ID | p_firstName | p_lastName | p_job1 | p_job2 |
+------+-------------+------------+--------+--------+
|   1  | Mike        | Jefferson  |      3 |      1 |
|   2  | Jack        | Frost      |      2 |        |
+------+-------------+------------+--------+--------+

表“tbl_job”

+--------+------------+
| job_ID |  job_Name  |
+--------+------------+
|      1 | Clerk      |
|      2 | Programmer |
|      3 | Mechanic   |
+--------+------------+

我想用tbl_job表中的job_Name显示tbl_person表。到目前为止,PHP代码本身正确地显示了页面刷新。但是,使用我当前的jQuery代码,只显示来自tbl_person的数据。

jQuery当前显示的示例(例如,使用一个显示所有条目):

+------+-----------+---+---+----+------+
| Mike | Jefferson | 3 | 1 |Edit|Delete|
+------+-----------+---+---+----+------+

php代码的功能示例/我想要jQuery代码执行的操作(例如,使用一个显示所有条目):

+------+-----------+----------+-------+----+------+
| Mike | Jefferson | Mechanic | Clerk |Edit|Delete|
+------+-----------+----------+-------+----+------+

代码的主要部分如下。我想在html表中显示我正在登录控制台的内容,以便它显示在网页上(见上表):

$.ajax({
    url: "person.php",
    type: 'POST',
    data: data,
    success: function (data) {
        console.log($("#job1 option:selected").text());
        console.log($("#job2 option:selected").text());
    },
    error: function () {
        //insert error alert
    }
});

函数pdo文件未包含(包含db函数)

带有输入数据和显示格式的PHP文件(html结构): person.php

//below code posts new info to database
<?php
$pdo = new functions();
$getPerson = $pdo->getPerson("");
$PersonList = $pdo->getPersonList();

if(isset($_POST["p_ID"])){
    if($_POST["p_ID"] != ''){
        $pdo->updatePerson($_POST);
    }else{
        $pdo->addPerson($_POST);
    }
exit();
}

if(isset($_GET["id"])) {
    $pdo->deletePerson($_GET["id"]);
}
?>

//html form for entering info (this should pop up with jQuery code when clicking new entry button

<div id="personform" title="Person Form">
<form name="personedit" id="personedit" method="post" action="person.php">
<!--//hidden section for the id to pass for the record update-->
<input name="p_ID" type="hidden" value="" />
<fieldset>
<legend>People</legend>
<table>
    <tr>
        <th><label for="p_firstName">First Name:</label><br /></th>
        <td><input type="text" class="name" name="p_firstName" value="" size="18" maxlength="25"/></td>
        <th><label for="p_lastName">Last Name:</label><br /></th>
        <td><input type="text" class="name" name="p_lastName" value="" size="18" maxlength="25"/></td>
    </tr>
    <tr>
        <th>First Job:</th>
        <td>
            <select name="p_job1" id="job1" class="name">
                <option value=""></option>
                <?php 
                    $getJobs = $pdo->getJobs();
                    foreach($getJobs as $row){  
                        if($row["job_ID"] == $getPerson["p_job1"]){
                            $selected = "selected = selected";
                        }else{
                            $selected = "";
                        }
                        echo "<option value='" . $row['job_ID'] . "' $selected>" . $row['job_name'] . "</option>";
                    }
                ?>                  
            </select>   
        </td>
        <th>Second Job:</th>
        <td>
            <select name="p_job2" id="job2" class="name">
                <option value=""></option>
                <?php 
                    foreach($getJobs as $row){  
                        if($row["job_ID"] == $getPerson["p_job2"]){
                            $selected = "selected = selected";
                        }else{
                            $selected = "";
                        }
                        echo "<option value='" . $row['job_ID'] . "' $selected>" . $row['job_name'] . "</option>";
                    }
                ?>                  
            </select>               
        </td>
    </tr>
</table>           
</fieldset>        
</form>
</div>

/*html code to display the person table data in table format with the job name 
displayed (not the id) */

<a class="add" href="person.php">New Entry</a>

<h1>Person List</h1>
<div class="float-left">
    <table id="tbllist">
        <tr>
            <th>Last Name</th>
            <th>First Name</th>
            <th>First Job</th>
            <th>Second Job</th>
            <th colspan="2">Action</th>
        </tr>
    <?php   
        foreach ($PersonList as $row) {
            echo "<tr class='fadeaway" . $row['p_ID'] . "'>";       
            echo "<td><input type='hidden' id='p_lastName".$row['p_ID']."' value='".$row['p_lastName']."'>".$row['p_lastName']."</td>";
            echo "<td><input type='hidden' id='p_firstName".$row['p_ID']."' value='".$row['p_firstName']."'>".$row['p_firstName']."</td>";
            echo "<td><input type='hidden' id='job_Name1".$row['p_ID']."' value='".$row['p_job1']."'>".$row['job_Name1']."</td>";
            echo "<td><input type='hidden' id='job_Name2".$row['p_ID']."' value='".$row['p_job2']."'>".$row['job_Name2']."</td>";
            echo "<td><a href='#' class='edit' id='".$row['p_ID']."'>Edit</a></td>";
            echo "<td><a href='#' class='delete' id='".$row['p_ID']."'>Delete</a></td>";
            echo "</tr>";
        }
    ?>
    </table>
</div>

Javascript代码的一部分     

//this section is in a separate js file 
// JavaScript Document
function() {
    var data = $($(this).data('formID')).closest("form").serialize();   

    if($($(this).data('formID')).valid()){  
        var ID = $(this).data('ID'); //gets ID of table row for editing

        //This function finds the class name of each input for use in the add section
        var inputname = $(".name").map(function() {
            r = $(this).attr("name");
            return r;
        }).get();

        //This function finds the value of each input for use in the add section
        var inputval = $(".name").map(function() {
            p = $(this).val();
            return p;
        }).get();

        //code to change array positioning so that the table is printed correctly.


        /*AJAX code for name value (this is what needs to be changed) */
        $.ajax({
            url: "person.php",
            type: 'POST',
            data: data,
            success: function (data) {

            },
            error: function () {
                alert('Sorry, there was a problem!');   
            }
        });

        $.ajax({
            'url': '',
            'type': 'POST',
            'dataType': 'text', 
            'data': data,
            'success': function(data){

                if (action == "edit") {

                    var tblval = "";
                    //loops through the number of input names and adds a table value for each one
                    for (i = 0; i < inputname.length; i++) {
                        console.log(inputval[i]);
                        var val = inputval[i];
                        var tblval = tblval + "<td><input type='hidden' id="+inputname[i]+ID+" value='"+val+"'>"+val+"</td>";
                    }
                    edit = $("#tbllist .fadeaway"+ID+"").html(tblval+"<td><a href='#' class='edit' id='"+ID+"'>Edit</a></td>"+"<td><a href='#' class='delete' id='"+ID+"'>Delete</a></td>");
                }

            }
        });
    }
}

我对AJAX和jQuery相当新,所以这些代码可能不是最佳实践。

1 个答案:

答案 0 :(得分:0)

我编写的代码还有其他问题,但我通过更改此部分解决了这个问题:

var inputval = $(".name").map(function() {
    p = $(this).val();
    return p;
}).get();

到此:

var inputval = $(".name").map(function() {
    if (!$(this).is("select")) {    
        p = $(this).val();
    } else {
        p = $(this).find("option:selected").text();
    }
    return p;
}).get();