将mysql(php)值拉入json->错误未定义

goqiplq2  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(219)

我正在尝试从mysql推送信息,在一个名为edit\u v的php文件中,在我的主文件editar\u v中,我想填充表单中的输入字段,这样,用户就可以编辑与存储在我数据库中的车辆相关的信息。为此,我使用ajax,这样页面就不会被重新加载/更改。
下面是我的editar_v.php主要代码:

<div class="container-fluid">
  <div class="row">
      <div class="col-md-12">
        <form method="POST" action="editar_v.php">
            <div class="form-row">
                <div class="form-group col-md-12">
                    <label for="input_veiculo_editar">Escolha o veículo que pretende editar:</label>
                    <select class="custom-select my-1 mr-sm-2" id="dropdown_matricula">   
                    <option selected>Veículos Disponíveis</option>
                    <?php 
                        $conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
                        $sql = "SELECT id, matricula FROM veiculo";
                        $result = $conn->query($sql);

                        if($result->num_rows > 0)
                        {
                            while($row = $result->fetch_assoc()) {
                            echo "<option value='".$row['id']."'>".$row['matricula']."</option>";                      
                            }
                        }    
                    ?>
                    </select>
                </div>
            </div>

            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for"input_marca">Marca do Veículo:</label>
                    <input type="text" class="form-control" id="input_marca" disabled value="NOTHING">
                </div>
                <div class="form-group col-md-6">
                    <label for="input_modelo">Modelo do Veículo:</label>
                    <input type="text" class="form-control" id="input_modelo" disabled>
                </div>
            </div>  
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for"input_cilindrada">Cilindrada (CV):</label>
                    <input type="text" class="form-control" id="input_cilindrada" disabled>
                </div>
                <div class="form-group col-md-6">
                    <label for="input_potencia">Potencia do Veículo:</label>
                    <input type="text" class="form-control" id="input_potencia" disabled>
                </div>
            </div>
            <div class="form-group">
                <label for="input_combustivel">Combustível:</label>
                <input type="text" class="form-control" id="input_combustivel" disabled>
            </div>
            <div class="form-row">
                <div class="form-group col-md-6">
                    <label for"input_ano">Ano do Veículo:</label>
                    <input type="text" class="form-control" id="input_ano" disabled>
                </div>
                <div class="form-group col-md-6">
                    <label for="input_modelo">Modelo do Veículo:</label>
                    <input type="text" class="form-control" id="input_modelo" disabled>
                </div>
            </div>  
            <div class="form-group">
                <label for="input_escolaID">Escola de Condução a que pertence:</label>
                <select class="custom-select my-1 mr-sm-2" id="inlineFormCustomSelectPref" disabled>   
                <option selected></option>
                <?php 
                    $conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
                    $sql = "SELECT id_escola, nome FROM escola";
                    $result = $conn->query($sql);

                    if($result->num_rows > 0)
                    {
                        while($row = $result->fetch_assoc()) {
                        echo "<option value='".$row['id_escola']."'>".$row['nome']."</option>";                      
                        }
                    }    
                ?>
                </select>
            </div>
        <input type="button" value="Procurar Veículo" id="procuraveiculo">
        <input type="button" value="Editar Veículo" id="adicionar_veiculo">
        <span id="jsonresultado"></span>
        </form>
      </div>
  </div>
</div>

在同一个文件中,我有以下javascript/jquery:

<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

<script type="text/javascript">
    $(document).ready(function(){
        console.log("Document ready!");
        $("#procuraveiculo").on('click', function() {
            var e = document.getElementById("dropdown_matricula");
            var strUser = e.options[e.selectedIndex].text;
            alert(strUser);

            $.ajax({
                method: "POST",
                url: "admin_pages/veiculo_pages/edit_v.php",
                data: {matriculaPHP:strUser},

                complete: function(data) {
                    var yourDataStr = JSON.stringify(data);
                    var result = yourDataStr;
                    console.log(result[0].marca);

                },
                error : function (data) {
                    console.log("error:"+data.message);
                    console.log("DATA ERROR:: " + data.msg);
                },
                dataType: "JSON",
            });

        });
    });
</script>

因此,在这部分代码中,我为用户提供了在数据库中选择一辆可用车辆的选项。之后,我将它发送到matriculaphp中的php文件中,这样就可以正常工作了。
下面是我的edit_v.php:

<?php

         $conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
         $matricula = $_POST['matriculaPHP'];
         $sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
         $result = $conn->query($sql);

        if($conn->query($sql) == TRUE)
        {
             echo "Base de dados conectada!";
        }
        else
        {
            echo "Error " . $sql . "<br>" . $conn->error;
        }

        $data = array();

        while($row = $result->fetch_assoc()) {
            $data[] = $row;  
        }
        print json_encode($data);
        header('Content-type: application/json');
        echo json_encode($data);          

?>

结论:当我执行代码时,我从数据库中得到了正确的值。示例:[{“marca”:“雪铁龙”,“modelo”:“c3”,“cilindrada”:“1100”,“Potenia”:“60”,“combustivel”:“gasolina”,“ano”:“2002”,“mes”:“6”,“escola\u id\u escola”:“1”}]
但是,当我尝试读取json/javascript中的代码时,它会给我一个错误:undefined。
我想得到你的一些帮助,这样我就可以解决这个问题,并继续在我的项目工作。

f45qwnt8

f45qwnt81#

已解决

在这个大社区的帮助下,我终于解决了我的问题!
editar_v.php jquery:

$("#procuraveiculo").on('click', function() {
            var e = document.getElementById("dropdown_matricula");
            var strUser = e.options[e.selectedIndex].text;
            alert(strUser);

            $.ajax({
                method: "POST",
                url: "admin_pages/veiculo_pages/edit_v.php",
                data: {matriculaPHP:strUser},

                success: function(data) {
                    var marca = data[0].marca;
                    var modelo = data[0].modelo;
                    var cilindrada = data[0].cilindrada;
                    var potencia = data[0].potencia;
                    var combustivel = data[0].combustivel;
                    var ano = data[0].ano;
                    var mes = data[0].mes;
                    var idEscola = data[0].escola_id_escola;

现在,php文件:edit\u v.php:

<?php
header('Content-type: application/json');

$res=array(
    'success' => false,
    'errors' => array(),
    'data' => null
);

$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo");
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);

if($conn->query($sql) == TRUE)
{
    // echo "Base de Dados conectada!";
    $res['success'] = true;
    $res['data'] = array();

    while($row = $result->fetch_assoc())
    {
        $res['data'][] = $row;
    }
}
else
{
    $res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}

echo json_encode($res['data']);
?>

这工作得非常好,现在我确实了解jquery在这种情况下是如何工作的。我也明白我在php中的错误。
感谢@omari celestine和@norbul以及stackoverflow社区。

y4ekin9u

y4ekin9u2#

首先,由于打印数据库连接状态的行,edit_v.php文件没有输出有效的json。
如果要这样做,则必须将所有数据作为数组的一部分输出。
例如:

header('Content-type: application/json');

$res = array(
    'success' => false,
    'errors' => array(),
    'data' => null
);

$conn = new mysqli("localhost", "root", "", "escolas_conducao_semprefundo")
$matricula = $_POST['matriculaPHP'];
$sql = "SELECT marca, modelo, cilindrada, potencia, combustivel, ano, mes, escola_id_escola FROM veiculo WHERE matricula='$matricula'";
$result = $conn->query($sql);

if($conn->query($sql) == TRUE)
{
    // echo "Base de dados conectada!";
    $res['success'] = true;
    $res['data'] = array();

    while ($row = $result->fetch_assoc())
    {
        $res['data'][] = $row;
    }
}
else
{
    $res['errors'][] = "Error " . $sql . "<br>" . $conn->error;
}

echo json_encode($data);

此外,还有 Content-Type 在进行任何输出之前,必须设置标题。
在jquery请求的完整函数中,您将使用 JSON.stringify(...) 这不应该。你应该试着换一下衣服 complete 函数到 success 并按原样使用数据。

...
success: function(data) {
    console.log(data[0].marca);
},
...
mbjcgjjk

mbjcgjjk3#

问题在于javascript和phpjson。当数组中只有一个元素时,就没有记录0。请使用代码:console.log(data.marca)而不是console.log(data[0].marca),您将看到结果。您必须检查json中是否只有一个元素数组或几个元素数组,然后使用正确的代码。

相关问题