无法从服务器端获取数组

时间:2019-02-06 17:22:14

标签: javascript php arrays ajax

我想从php脚本中获取一些数据到我的html页面。它们的数组$ UniqueNames在服务器端具有一个值,但是当我在html页面上使用json_encode时似乎什么也没发生,console.log返回一个空数组(BilderID)。有什么建议吗?

代码:

MK_BITS

Php:

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

1 个答案:

答案 0 :(得分:-2)

解决方案是删除数据类型说明符,在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仍能找出原因,为什么要使用“数据类型”?