Не могу получить массив со стороны сервера - PullRequest
0 голосов
/ 06 февраля 2019

Я хочу получить некоторые данные из php-скрипта на мою html-страницу.У них массив $ UniqueNames имеет значение на стороне сервера, но, кажется, ничего не происходит, когда я использую json_encode на html-странице, console.log возвращает пустой массив (BilderID).Есть предложения?

код:

<script>
var BilderID = [];
$(document).ready(function (e) {
    $('#SubmitBild').on('click', function () {
        var form_data = new FormData();
        var ins = document.getElementById('Myfilefield').files.length;
        for (var x = 0; x < ins; x++) {
            form_data.append("Bilder[]", document.getElementById('Myfilefield').files[x]);
        }
        $.ajax({
            url: 'Includes/Bildhantering.php', // point to server-side PHP script
            dataType: 'text', // what to expect back from the PHP script
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (response) {
                $('#msg').html(response); // display success response from 
            },
            error: function (response) {
                $('#msg').html(response); // display error response from the PHP script
            }
        });

        BilderID = <?php echo json_encode($UniqueNames); ?>

        console.log(BilderID);

    });
});
</script>

Php:

$UniqueNames = array();    

for($i=0;$i<count($file_array);$i++)
{
    if($file_array[$i]['error']){
        echo $phpFileUploadErrors[$file_array[$i]['error']];
    } else {
        $extensions = array('jpg','png','gif','jpeg');
        $file_ext = explode('.',$file_array[$i]['name']);
        $file_ext = end($file_ext);

        if (!in_array($file_ext, $extensions)){
            echo "Invalid file extension!";
        } else {
            $fileNameNew = uniqid('', true).".".$file_ext;
            $UniqueNames[] = $fileNameNew;

            move_uploaded_file($file_array[$i]['tmp_name'], 'Bilder/'.$fileNameNew);
            echo $phpFileUploadErrors[$file_array[$i]['error']];
        }
    }
}

1 Ответ

0 голосов
/ 07 февраля 2019

Решение состояло в том, чтобы удалить спецификатор типа данных, вывести массив в php и получить его в методе успеха:

  $.ajax({
            url: 'Includes/Bildhantering.php', // point to server-side PHP script
            //dataType: 'text', // what to expect back from the PHP script
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,
            type: 'post',
            success: function (response) {
              BilderID = response;
              console.log(BilderID);
            },
            error: function (response) {
                console.log("error:");
            }
        });

Я имею в виду, зачем использовать «тип данных», если javascript все равно его вычисляет?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...