检索部分jquery响应以填充输入和选择

时间:2016-07-19 17:57:46

标签: javascript php jquery mysql ajax

我将一个jQuery请求(包含business_id)发送到php文件,以检索数据库中的所有值,以填充字段并选择我的表单中的字段并对应于此id。但是,我如何才能从数据库中检索响应?这样我就可以使用数据库中的值提供表单中的字段和选择。我的javascript函数如下所示:

businessselect: function(){

    $('#busselect').change(function() {
        opt = $(this).val();

        if (opt=="new_bus") {

            location.reload();

        }
        else
        {
            businessid = $(this).children(":selected").attr("id");

            $.ajax({
             url : "businessdata.php",
             method : "post",
             data : "business_id="+businessid,
             success: function(response) { 
                 $("#uitgevoerd_door_naam").val(response);
             }
         });
        }
    });
},

我的businessdata.php如下所示:

<?php

$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");

if ($mysqli->connect_errno) {
   printf("Connect failed: %s\n", $mysqli->connect_error);
   exit();
}

 if($_POST)
 {

   $result = $mysqli->query("SELECT * from form WHERE ID ='$_POST[business_id]'");
   while ($row = $result->fetch_assoc()) {
    echo $row['uitgevoerd_door_naam'];
    echo $row['hoev_gev_stof_score'];
   }

}

mysqli_close($mysqli);

?>

我想要实现的目标是:

$("#uitgevoerd_door_naam").val() == $row['uitgevoerd_door_naam'];
$("#hoev_gev_stof_score").val() == $row['hoev_gev_stof_score'];

等.....

1 个答案:

答案 0 :(得分:0)

修正:

使用json encode:

功能:

businessselect: function(){

    $('#busselect').change(function() {
        opt = $(this).val();

        if (opt=="new_bus") {

            location.reload();

        }
        else
        {
            businessid = $(this).children(":selected").attr("id");

            $.ajax({
             url : "businessdata.php",
             method : "post",
             dataType: "json",
             data : "business_id="+businessid,
             success: function(response) { 

                 $("#uitgevoerd_door_naam").val(response.a); 
                 $("#riskpot_scorefield3").val(response.b); 
             }
         });
        }
    });
},

php文件:

<?php

$mysqli = new mysqli("localhost", "root", "", "brandveiligheid");

if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}

if($_POST)
{

$result = $mysqli->query("SELECT * from form WHERE ID = '$_POST[business_id]'");
while ($row = $result->fetch_assoc()) {
    echo json_encode(array("a" => $row['uitgevoerd_door_naam'], "b" => $row['hoev_gev_stof_score']));
}

}

mysqli_close($mysqli);

?>