我可以从脚本标签调用数据库数据吗?

时间:2018-11-08 01:22:49

标签: php html

我需要从数据库中调出其他数据,但是我的id变量在javascript中,有什么办法可以做到这一点?还是我应该尝试使用其他方法?

我的PHP

<?php
$connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
mysql_select_db('ts_php');
$query = "SELECT * FROM job_posted"; //You don't need a ; like you do in SQL
$result = mysql_query($query);
echo "<table class='table'>
        <thead>
                  <th>JOB</th>
                  <th>STATUS</th>
                  <th>APPLICATIONS</th>
                  <th>EDIT</th>
                  <th>DELETE</th>
        </thead>


    "; // start a table tag in the HTML

while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
    echo "<tr>
            <th>" . $row['job_title'] . "</th>
                <td>" . $row['status'] . "</td>
                <td>" . $row['applications'] . "</td>
                <td><a class='openModal' data-id='".$row['post_ID']."' >edit</a></td>
                <td><a href='#'>delete</a></td>                  
            </tr>";
    }

echo "</table>"; //Close the table in HTML

    ?>

我的脚本

<script>
    $(".openModal").click(function(){
    var job_posted_id = $(this).data('id');
    $(".modal-body").html("This is your post id " + job_posted_id + "<br> This is where i want all my data");
        $(".modal").modal("show");
});
</script>

1 个答案:

答案 0 :(得分:1)

您可以使用ajax:

$(".openModal").click(function(){
    var job_posted_id = $(this).data('id');
    $.get('your_function.php', {'job_posted_id':job_posted_id}, function(data) {
        $(".modal-body").html(data);
        $(".modal").modal("show");
    }, 'json');
});

您的php:

if (isset($_GET['job_posted_id']) {

    $connection = mysql_connect('localhost', 'root', ''); //The Blank string is the password
    mysql_select_db('ts_php');
    $query = "SELECT * FROM job_posted WHERE `job_posted_id` = ". $_GET['job_posted_id']; //You don't need a ; like you do in SQL
    $result = mysql_query($query);
    $str = "<table class='table'>
            <thead>
                      <th>JOB</th>
                      <th>STATUS</th>
                      <th>APPLICATIONS</th>
                      <th>EDIT</th>
                      <th>DELETE</th>
            </thead>


        "; // start a table tag in the HTML
    while($row = mysql_fetch_array($result)){   //Creates a loop to loop through results
        $str .= "<tr>
                <th>" . $row['job_title'] . "</th>
                    <td>" . $row['status'] . "</td>
                    <td>" . $row['applications'] . "</td>
                    <td><a class='openModal' data-id='".$row['post_ID']."' >edit</a></td>
                    <td><a href='#'>delete</a></td>                  
                </tr>";
        }

    $str .= "</table>"; //Close the table in HTML

    echo $str;
}
相关问题