JQuery ajax/PHP数组交互

JQuery ajax/PHP数组交互,php,html,arrays,Php,Html,Arrays,当我在浏览器中加载此代码时,只有一个警报窗口(' 我只想从我的PHP文件中获取多个元素 main.html: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script> $(document).ready(function(){ $

当我在浏览器中加载此代码时,只有一个警报窗口(' 我只想从我的PHP文件中获取多个元素

main.html:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
    $.get("test.php", function(data, status){
        alert(data[0] + data[1]);
    });
});
});
</script>
</head>
<body>

<button>clic</button>

</body>
</html>

$(文档).ready(函数(){
$(“按钮”)。单击(函数(){
$.get(“test.php”,函数(数据、状态){
警报(数据[0]+数据[1]);
});
});
});
clic
和test.php:

<?php
$data = array();
require ('steamauth/steamauth.php');
if(!isset($_SESSION['steamid'])) {
$data[0] = "test00";
$data[1] = "test01";
echo $data[];
}  else {
include ('steamauth/userInfo.php');
$data[0] = "test0";
$data[1] = "test1";
echo $data[];
}    
?>

多谢各位
弥敦

< p>你的jQuery看起来很好,但是如果你的目标是“代码> $(“按钮”),这将监听该页面上的所有按钮。考虑给它一个ID。对于这个例子,我把它更新到:

$(document).ready(function(){
    $("button").click(function(){
        $.get("test.php", function(data){
            alert(data.foo + data.bar);
        });
    });
});
在PHP文件中,您没有输出JSON编码结果。您需要将内容类型添加到
标题()
,然后使用
JSON\u encode()
。对于本例,为了维护,我没有使用assoc数组

header('Content-Type: application/json');
session_start(); // Your missing this unless Steamauth.php contains it

$data = array();
require ('steamauth/steamauth.php');

if(!isset($_SESSION['steamid'])) {
    $data['foo'] = "test00";
    $data['bar'] = "test01";
    echo json_encode($data);
} else {
    include ('steamauth/userInfo.php');
    $data['foo'] = "test0";
    $data['bar'] = "test1";
    echo json_encode($data);
}    

注意,如果steamauth不包含
session\u start()
,则
$\u session
将被取消设置。

echo$data[];
不正确(如果启用了错误报告,则可以看到响应错误)。
json\u encode
然后
echo
echo$data[]
还会抛出一个
致命错误,无法使用[]读取行号x
当您要显示数组时,必须编写print\u r()而不是echo。@Melody print\u r()不是在两种语言之间传输数据的好选择……它有助于在调试时快速查看。使用“echo json\u encode($data)“,我仍然有相同的错误(弹出窗口”