如何在php中拆分数组并传递给javascript变量?

时间:2019-03-22 06:25:19

标签: javascript php arrays

我有一个数组来自php文件。

"[{\"username\":\"a.villar026\",\"fullname\":\"Alexis Abulencia Villar\"}]"

这是在MYSQL表中检索的php文件中的数组设置。那么我想获取数组的用户名和全名的值,但是当我将其作为javascript变量返回时,结果为undefined

我尝试了以下代码:

var user = JSON.stringify(msg.username);
var name = JSON.stringify(msg.fullname);

var user = JSON.stringify(msg[0]['username']);
var name = JSON.stringify(msg[0]['fullname']);

var user = JSON.stringify(msg[0]); //this returns only an character ({) or {[}
var name = JSON.stringify(msg[1]); //this returns only an character ({) or {[}

我的问题是,如何使用php数组设置javascript中变量的值。

其他信息:

JAVASCRIPT代码:

$(document).ready(function(){
        $("#logout").click(function(){

        });
    getUser();
 });

    function getUser(){
    var user ='';
    var session ='';
        $.ajax({
                type:'POST',
                url:'../bench/php/session.php',
                data:'',
                success:function(msg){
                    alert(JSON.stringify(msg));
                     user = JSON.stringify(msg.username);

                    console.log(JSON.stringify(user));
                }, error: function(e){
                    console.log(e);
                }
            });
    }

PHP代码:

<?php
   include('config.php');
   session_start();

   $user_check = $_SESSION['login_user'];
   $temparray = array();

      $ses_sql = mysqli_query($db,"select username,fullname from user where username = '$user_check'");

      $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

        if ($row > 0 ){         
                array_push($temparray, $row); //save your data into array
        }

       echo json_encode($temparray);

       if(!isset($_SESSION['login_user'])){
          header("location:index.html");
       }

?>

1 个答案:

答案 0 :(得分:2)

  

如何使用php数组在javascript中设置变量的值。

let response = "[{\"username\":\"a.villar026\",\"fullname\":\"Alexis Abulencia Villar\"}]"
let data = JSON.parse(response)
console.log(data)
data[0].username = "something"
console.log(data)