【问题标题】:PHP passing JSON data using Ajax for inArray() comparisonPHP 使用 Ajax 传递 JSON 数据以进行 inArray() 比较
【发布时间】:2023-03-22 15:05:01
【问题描述】:

我正在尝试使用 Ajax 将 html 表单中的用户输入检查到数据库中的允许值列表,然后我想显示相应的消息。这是我正在使用的代码:

js

$(document).ready(function(e){

  $.ajax({
    type: 'POST',
    url: 'datafile.php',
    dataType : "json",
    success: function(result) {
          $("#postal_code").change(function(){
            var postal_code = $("#postal_code").val().slice(0,-2);
            if ($.inArray(postal_code,result) !== -1){
             console.log('success');
            } else {
              console.log('failure');
            }
        });
      }
    });
  });

数据文件.php

<?php
require_once("./db_con.php");

$query = mysqli_query($con, "SELECT postal_code FROM table");
$rows = mysqli_fetch_all($query);
echo json_encode($rows);
mysqli_free_result($query);
mysqli_close($con);
exit();
?>

我遇到的问题是输入值永远不会匹配result 变量中的任何值,即使我知道它们在数据库中。我认为这个问题与result 变量包含另一个数组中的数组有关,例如[["value1"],["value2"],["value3"]].

【问题讨论】:

    标签: php jquery json ajax


    【解决方案1】:

    我不能真正谈论 JavaScript 部分,但由于您只选择一列,您可以将其提取到一个维度中。 mysqli_fetch_all 默认获取数字索引数组:

    $rows = array_column(mysqli_fetch_all($query), 0);
    

    或者按列名获取和提取:

    $rows = array_column(mysqli_fetch_all($query, MYSQLI_ASSOC), 'postal_code');
    

    【讨论】:

    • 感谢在服务器端使用array_column() 解决了问题!
    猜你喜欢
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多