【发布时间】:2019-02-06 17:22:13
【问题描述】:
我想从 php 脚本获取一些数据到我的 html 页面。它们的数组 $UniqueNames 在服务器端有一个值,但是当我在 html 页面上使用 json_encode 时似乎什么也没发生,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']];
}
}
}
【问题讨论】:
-
dataType 应该设置为 json - 而不是 text
-
@treyBake 仍然没有。
-
他没有从 PHP 文件中输出任何 JSON...
-
您将服务器端与前端/DOM 混合在一起,按照您的设置方式,它不会起作用。
-
哦等等……你为什么在你的 jquery 脚本中回显 PHP 变量?使用响应..
标签: javascript php arrays ajax