AJAX - 在选择输入中更改事件时更改元素的 innerHTML 不起作用

<select>当用户在元素中进行选择并在元素中显示通过 AJAX 获得的所述值但它不起作用时,我试图从数据库中获取产品的值,如果我去precio.php?q=PRODUCTO%201它确实给了我想要的10结果让我认为 php 文件中的代码是正确的,问题必须存在于<script>部分或<select>元素中。


这是我的 AJAX 函数<head>


<script>

    function precioProd(str) {

        if (str=="") {

            document.getElementById("precio").innerHTML="";

            return;

        }

        if (window.XMLHttpRequest) {

            var xmlhttp = new XMLHttpRequest();

        }

        xmlhttp.onreadystatechange = function() {

          if (this.readyState == 4 && this.status == 200) {

            document.getElementById("precio").innerHTML = this.responseText;

          }

        };

        xmlhttp.open("GET", "precio.php?q="+str, true);

        xmlhttp.send();

      }

    }

</script>

这是我的<select>元素<body>


<div class="form-group row">

    <label class="col-sm-4 col-form-label font-weight-bold">Elige un Producto</label><br>

    <div class="col-sm-8">

        <select class="custom-select my-1 mr-sm-2" id="producto" name="producto" onchange="precioProd(this.value)" required>

            <option selected>Elegir...</option>

    <?php require $_SERVER['DOCUMENT_ROOT'].'/php/fetch_lista_productos_compra.php'; ?>

        </select>

    </div>

</div>

<h3 id="precio" name="precio"></h3>

这是内容precio.php


<?php 

require $_SERVER['DOCUMENT_ROOT'].'/php/db_key.php';


$con = mysqli_connect($servername, $username, $password, $dbname);


$q = $_GET["q"];


$sql = "SELECT precio FROM productos WHERE titulo = '".$q."'";


$result = mysqli_query($con,$sql);


while($row = mysqli_fetch_array($result)) {

    echo $row['precio'];

}

?>

一如既往,我们将不胜感激任何形式的帮助,并感谢您抽出宝贵的时间。


撒科打诨
浏览 140回答 1
1回答

德玛西亚99

}您在脚本末尾添加了一个附加项。以下是可以的。<script>&nbsp; &nbsp; function precioProd(str) {&nbsp; &nbsp; &nbsp; &nbsp; if (str=="") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("precio").innerHTML="";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (window.XMLHttpRequest) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var xmlhttp = new XMLHttpRequest();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp.onreadystatechange = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("precio").innerHTML = this.responseText;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; };&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp.open("GET", "precio.php?q="+str, true);&nbsp; &nbsp; &nbsp; &nbsp; xmlhttp.send();&nbsp; &nbsp; }</script>
打开App,查看更多内容
随时随地看视频慕课网APP