Javascript 通过AJAX请求php文件上的数组

Javascript 通过AJAX请求php文件上的数组,javascript,php,ajax,processwire,Javascript,Php,Ajax,Processwire,我需要一个数组。我有一个ProcessWire页面,页面和子页面以及这些页面和子页面上的字段。我把这些信息打包成一个数组,就像这样 <?php $allarticles = $pages->find("template=article"); // find by template of the last level $catalogue = array(); $i = 0; foreach ($allarticles as $onearticle)

我需要一个数组。我有一个ProcessWire页面,页面和子页面以及这些页面和子页面上的字段。我把这些信息打包成一个数组,就像这样

<?php

    $allarticles = $pages->find("template=article"); // find by template of the last level
    $catalogue = array();
    $i = 0;

    foreach ($allarticles as $onearticle) {
        $temp = array ( // create a temporary array for the lowest level
            'id' => $onearticle->id,
            'title' => $onearticle->title,
            'coverimage' => $onearticle->cover->url,
            'url' => $onearticle->url,
            'author' => $onearticle->author,
            'date' => $onearticle->date,
            'year' => $onearticle->parent->parent->title,
            'issue' => $onearticle->parent->title,
            'offline' => $onearticle->offline,
            'body' => $onearticle->body
        );
        $catalogue[$i] = $temp; // add the results of each foreach (i.e. an array) to the main array at position $i 
        $i++; // go to the next position of the main array 

    };

    print_r ($catalogue);

?>

这似乎是一种工作

代码位于根文件夹中的test.php中

现在我试图通过AJAX请求这个php文件

<script type="text/javascript">

    var request = new XMLHttpRequest();
    if (request) {
        request.onreadystatechange = ReloadRequest;
        request.open("GET", "test.php", true);
        request.send(null);
    } 

    function ReloadRequest() {
        request.readyState;
        var str = request.responseText;
        document.getElementById("boxedcontent").innerHTML = (str);
    }

</script>

var request=new XMLHttpRequest();
如果(请求){
request.onreadystatechange=重新加载请求;
open(“GET”、“test.php”、true);
请求发送(空);
} 
函数重载请求(){
request.readyState;
var str=request.responseText;
document.getElementById(“boxedcontent”).innerHTML=(str);
}
此脚本位于应用于特定页面的模板文件的底部

js代码在请求html文件时有效,但在php文件中无效。我收到一个“(内部服务器错误)服务器响应状态为500”


谢谢你的帮助

首先在php文件中将print\u r($catalouge)转换为echo json\u encode($catalouge);因此,php脚本将返回可理解的javascript格式

其次,将javascript代码替换为以下代码:

fetch('test.php')
.then( response=>response.text())
.then(data=> {
    document.getElementById("boxedcontent").innerHTML = data;

 });

Fetch api是一个非常简单且功能强大的javascript工具,用于发出ajax请求。

首先让PHP以JSON的形式传递数据。Javascript不理解来自
PHP print\u r()
的输出,这就是所有的PHP文件吗?我这样问是因为你没有实例化
页面
任何地方的500可能与你的服务器或processwire有关,我试图回答测试你的代码,它工作得很好。CMS框架预先编写并附加php代码。此外,所有页面基本上都是对象,您可以使用API返回这些对象。因此,
$pages
是预定义的,方法
->parent
->find(“选择器”)
等也是预定义的。检查或包括您的服务器日志?感谢您的努力,但
fetch
也不起作用。错误保持不变,并且保持为空。请检查服务器端代码并确保其正常工作,然后重试此代码。