-1

我需要一个数组数组。我有一个 ProcessWire 页面,其中包含页面和子页面以及这些页面和子页面上的字段。我将这些信息打包在一个数组中,就像这样……</p>

<?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>

此脚本位于应用于特定页面的模板文件的底部。

js 代码在请求 html 文件时有效,但不适用于 php 文件。我收到“ (内部服务器错误)服务器以状态 500 响应”

感谢帮助!

4

1 回答 1

0

首先在您的 php 文件中将 print_r($catalouge) 转换为 echo json_encode($catalouge); 所以你的 php 脚本会将可理解的格式返回给 javascript。

其次用以下内容替换您的javascript代码:

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

 });

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

于 2020-05-12T13:58:12.127 回答