weixin_33716941 2015-07-29 22:41 采纳率: 0%
浏览 14

PHP数组和Ajax响应

I am currently trying to call a php script through Ajax so I can read it in my html file. I am using Json and Ajax to achieve this. I am having an issue with my php script where I can't get the information to format correctly when sending it over to the html. Here's my php:

$return_arr = array();
$fetch = mysqli_query("SELECT User_Id, First_Name, Last_Name FROM Users"); 

while ($row = mysqli_fetch_array($fetch, MYSQLI_ASSOC)) {
    $row_array['User_Id'] = $row['User_Id'];
    $row_array['First_Name'] = $row['First_Name'];
    $row_array['Last_Name'] = $row['Last_Name'];
    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

I am getting the following type of response:

[{"User_Id":"6","First_Name":"Joe","Last_Name":"Shmo"},
{"User_Id":"17","First_Name":"Test","Last_Name":"Test"},
{"User_Id":"18","First_Name":"Test","Last_Name":"Test"},
{"User_Id":"19","First_Name":"Test","Last_Name":"Test"},
{"User_Id":"21","First_Name":"HI","Last_Name":"HI"}]

Now this causes me to have troubles while accessing in the html. I am trying to access it like:

data[0].User_Id

This gets undefined. I suspect the brackets are in the wrong places but can figure out how to switch them around.

  • 写回答

1条回答 默认 最新

  • 妄徒之命 2015-07-29 22:43
    关注

    You need to do something like this:

    <?php
    
    header('Cache-Control: no-cache, must-revalidate');
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
    header('Content-type: application/json');
    
    echo json_encode( $return_arr );
    
    评论

报告相同问题?