php - 选择多行放入数组并通过 AJAX 发送它们

标签 php jquery arrays ajax

我尝试在 PHP 中运行 SELECT 查询,然后选择多行,但我需要将它们提取到数组中,然后使用:echo json_encode($array)。之后我需要将此数组放入 AJAX 中。

这是 PHP 代码:

$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();

//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
    $arr[$i] = $row;
    $i++;
}

echo json_encode($arr);

问题是我无法将此数组的所有行放入 AJAX 中,因此我可以将它们附加到某个表中。这是脚本:

var txt = $("#txtSearch").val();
$.ajax({
    url: 'search.php', // Sending variable emp, pos, and sal, into this url
    type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
    data: {
        data1: txt
    }, //Now we can use $_POST[data1];
    dataType: "json", // text or html or json or script
    success: function(arr) {
        for() {
            // Here I don't know how to get the rows and display them in a table
        }
    },
    error:function(arr) {
        alert("data not added");
    }
});

最佳答案

您需要在成功回调中循环“arr”数据。大致如下:

var txt = $("#txtSearch").val();
$.ajax
({
    url: 'search.php', //Sending variable emp, pos, and sal, into this url
    type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
    data: {data1: txt},//Now we can use $_POST[data1];
    dataType: "json", //text or html or json or script

    success:function(arr)
    {
      var my_table = "";
      $.each( arr, function( key, row ) {
            my_table += "<tr>";
            my_table += "<td>"+row['employee_first_name']+"</td>";
            my_table += "<td>"+row['employee_last_name']+"</td>";
            my_table += "</tr>";
      });

      my_table = "<table>" + my_table + "</table>";

      $(document).append(my_table);
    },

    error:function(arr)
    {

        alert("data not added");

    }
    });

关于php - 选择多行放入数组并通过 AJAX 发送它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35571714/

相关文章:

javascript - 如果使用 chrome 中的上下文菜单粘贴,jquery 粘贴事件不会触发

javascript - 手动编辑嵌套数组

JavaScript 多维数组

php - Laravel SQL 查询返回错误结果

javascript - 在图像像素加载上提交表单

jQuery draggable and droppable with scroll on draggable ul

php - 从多个表中获取数据的最佳方式

切换到 mysqli 后 PHP 代码不再工作

php - 如何从 CodeIgniter 中的 URL 中删除 'index.php'?

php - 如何根据另一个表中的内容使用sql语句选择某些行