首页 > 解决方案 > 使用 Ajax 在组合框中显示数据

问题描述

我正在尝试使用 ajax 在我的组合框中显示我的数据库中的数据,但是然后我运行脚本我的组合框保持为空。

这是我的组合框

<select id="name" name="name">
    <option value= ""></option>
</select>

使用以下 PHP 脚本,我试图从我的数据库中选择数据:

<?php    
$servername = "localhost";
$username = "root";
$password = "pass";
$dbname = "db";

$conn = new mysqli($servername, $username, $password, $dbname) ;
if ($conn->connect_error) {
    die('Connection failed: ' . $conn->connect_error) ;
}else {

    $query = 'SELECT * FROM scu_stock';    
    $res = mysqli_query($conn, $query) ;
  if (mysqli_num_rows($res) > 0) {
     $result = mysqli_fetch_assoc($res) ;
    echo $result['name'];
  }else{
     $result = mysqli_fetch_assoc($res) ;
    echo "error";
  }    
} 
?>

以下代码应在组合框中输入数据:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script> 
  function getCode() { 
    console.log("getCode before ajax", jQuery('#name').val());
    jQuery.ajax({ 
      url: './get/get1.php', 
      method: 'POST', 
      data: {'id' : jQuery('#name').val()},
      success: function(response){ 
        console.log("getCode after ajax", jQuery('#name').val());
        jQuery('#name').val(response);
      }, 
      error: function (request, status, error) { 
        alert(request.responseText); 
      }, 
    });                 
  } 
</script>

脚本返回空,我看不到组合框中的任何更改。有人知道脚本有什么问题吗?

更新 1:

当我将组合框更改为文本框时,我可以看到文本框充满了数据。我无法在组合框中获取从数据库返回的数据。有人知道这个问题的解决方案吗?

这有效:

<input type="text" id="name" name="name" />

这不起作用:

<select id="name" name="name">
    <option value= ""></option>
</select>

标签: phpjqueryajax

解决方案


在您的情况下,响应应该是下面提到的格式的 JSON 数组。

 var response = [{"option": "option1", "value" : "option1"];

并且您需要根据您选择的某些条件选择默认选择的选项,例如选项值是否与某些特定字符串匹配。

要呈现选择选项,您可以通过以下方式更改代码。

 function getCode() { 
   console.log("getCode before ajax", jQuery('#name').val());
   jQuery.ajax({ 
      url: './get/get1.php', 
      method: 'POST', 
      data: {'id' : jQuery('#name').val()},
      success: function(response){ 
         console.log("getCode after ajax", jQuery('#name').val());
         //jQuery('#name').val(response); // change this line based on your default selected line condition
         $.each(response, function(index,json){
             jQuery('#name')
                .append($("<option></option>")
                .attr({"value": response, "selected":"selected"}).text(response));
            });
      }, 
      error: function (request, status, error) { 
         alert(request.responseText); 
      }, 
   });                 
 }

您也可以去掉波纹管,因为它将通过您的 JSON 响应填充,您不需要添加空白选项。

<option value= ""></option>

希望它能解决你的问题。


推荐阅读