将JavaScript数组传递给PHP文件将返回空数组

时间:2020-03-31 18:54:14

标签: javascript php

我正在尝试将javascript数组传递给PHP文件,如下所示:

JS文件中的代码

let directories =JSON.stringify(["John", "Sara", "Max"]);   
$.post('../test.php', {directories: directories});

在PHP文件中:

$directories = json_decode($_POST['directories']);

但是每次我得到一个空数组!我该如何解决?

更新

PHP

<?php
function getDirContents($directories, &$results = array()){

    $length = count($directories);
    for ($i = 0; $i < $length; $i++) {

    $files = array_diff(scandir($directories[$i]), array('..', '.'));;
    foreach($files as $key => $value){
        $path = $directories[$i].DIRECTORY_SEPARATOR.$value;
        if(is_dir($path)) {
          getDirContents($path, $results);
        } else {
          $directory_path = basename($_SERVER['REQUEST_URI']);
          $results[] =  'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
        }
    }

    }

    return $results;
}

$directories = json_decode($_POST['directories']);
print_r($_POST['directories'] 



echo json_encode(getDirContents($directories));

JavaScript

$(document).ready( function() {


    let directories =JSON.stringify(["recognition final tests", "4789"]);   
    $.post('../test.php', {directories: directories});

        $.ajax({
            type: 'POST',
            url: '../test.php',
            data: 'id=testdata',
            dataType: 'json',
            cache: false,
            success: function(result) {
            console.log(result);
            preload(result);

            },
        });
});




function preload(arr){
arr = arr.map(x => encodeURI(x));   
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
    typeof define === 'function' && define.amd ? define(factory) :
    (global.Preload = factory());
}(this, (function () { 'use strict';

    function preloadOne(url, done) {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
        xhr.responseType = 'blob';
        xhr.onprogress = event => {
            if (!event.lengthComputable) return false
            let item = this.getItemByUrl(event.target.responseURL);
            item.completion = parseInt((event.loaded / event.total) * 100);
            item.downloaded = event.loaded;
            item.total = event.total;
            this.updateProgressBar(item);
        };
        xhr.onload = event => {
            let type = event.target.response.type;
            let blob = new Blob([event.target.response], { type: type });
            let url = URL.createObjectURL(blob);
            let responseURL = event.target.responseURL;
            let item = this.getItemByUrl(responseURL);
            item.blobUrl = url;
            item.fileName = responseURL.substring(responseURL.lastIndexOf('/') + 1);
            item.type = type;
            item.size = blob.size;
            done(item);
        };

        xhr.onerror = event => {
        console.log('an error happed herrt')
    };

        xhr.send();
    }

    function updateProgressBar(item) {
        var sumCompletion = 0;
        var maxCompletion = this.status.length * 100;

        for (var itemStatus of this.status) {
            if (itemStatus.completion) {
                sumCompletion += itemStatus.completion;
            }
        }
        var totalCompletion = parseInt((sumCompletion / maxCompletion) * 100);

        if (!isNaN(totalCompletion)) {
            this.onprogress({
                progress: totalCompletion,
                item: item
            });
        }
    }

    function getItemByUrl(rawUrl) {
        for (var item of this.status) {
            if (item.url == rawUrl) return item
        }
    }

    function fetch(list) {  
        return new Promise((resolve, reject) => {
            this.loaded = list.length;
            for (let item of list) {
                this.status.push({ url: item });
                this.preloadOne(item, item => {
                    this.onfetched(item);
                    this.loaded--;
                    if (this.loaded == 0) {
                        this.oncomplete(this.status);
                        resolve(this.status);
                    }
                });
            }
        })
    }

    function Preload() {
        return {
            status: [],
            loaded: false,
            onprogress: () => {},
            oncomplete: () => {},
            onfetched: () => {},
            fetch,
            updateProgressBar,
            preloadOne,
            getItemByUrl
        }
    }

    return Preload;

})));


const preload = Preload();

preload.fetch(arr).then(items => {
  // use either a promise or 'oncomplete'
  console.log(items);
});

preload.oncomplete = items => {
  console.log(items);
}

preload.onprogress = event => {
  console.log(event.progress + '%');
}

preload.onfetched = item => {
  console.log(item);
}

};

更新2:

JS

$(document).ready( function() {


    let directories =JSON.stringify(["recognition final tests", "4789"]);   
    //$.post('../test.php', {directories: directories});

        $.ajax({
            type: 'POST',
            url: '../test.php',
            data: {directories: directories , id : "testdata"} ,
            dataType: 'json',
            cache: false,
            success: function(result) {
            console.log(result);
            preload(result);

            },
        });
});

PHP

$directories = json_decode($_POST['directories']);
print_r($_POST['directories'] 

还是我得到jquery-3.4.1.min.js:2 POST https://reed123.000webhostapp.com/test.php 500

1 个答案:

答案 0 :(得分:1)

尝试使用print_r($ _ POST)打印您的回复

您将看到您没有在请求的正文中发送{directories:directorys},在php中,您尝试获取数据:$ _POST ['directories'],因此您会收到服务器错误(状态为500)的响应

已更新:

最好只发送一个请求,然后发送所有数据。

    $.ajax({
        type: 'POST',
        url: '../test.php',
        data:  {directories: directories , id : "testdata"},
        dataType: 'json',
        cache: false,
        success: function(result) {
            console.log(result);
            preload(result);

        },
    });
});

并在您的php代码中:

print_r($_POST['directories']) ;

您还没有关闭普通话:)