选择多行进入数组并通过AJAX发送

时间:2016-02-23 07:51:33

标签: 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");
    }
});

3 个答案:

答案 0 :(得分:1)

你可以回来

json_encode($insertStmt->fetchAll());

另外,请务必仅检索UTF-8中的字符或JSON_encode将"崩溃"。

答案 1 :(得分:1)

你的成功功能应该是这样的:

success:function(arr)
    {
        $.each(arr,function (i,item) {

           alert(item.YOUR_KEY);
        });
    }

答案 2 :(得分:1)

你需要遍历你的" 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");

    }
    });