我尝试使用tutorial from codecourse/phpacademy进行拖放上传字段,但经过几个小时的尝试并弄清楚为什么我没有得到我的预期,我就去睡觉了第二天试试。
两天后,我迷路了。
我正在尝试创建一个div,用户可以删除多个图像,这些图像会立即上传到服务器。服务器响应应该是一个JSON字符串,其中包含一个或多个数组,其中包含上载文件的名称和路径。然后,此JSON字符串用于在上载页面上显示文件的名称。
工作原理:
什么不起作用:
通过这看起来,在JSON.parse接收其内容的行中停止我的javascript而没有错误消息。 编辑:我收到错误,感谢 arve0 ,"意外的令牌",但没有显示令牌。
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for(x = 0; x < files.length; x = x + 1) {
formData.append('files[]', files[x]);
}
try {
console.log("DING!1");
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log("DING!2");
displayUploads(data);
console.log("DING!3");
} catch(e) {
alert(e); //error in the above string(in this case,yes)!
}
xhr.open('post', 'url_to_upload_images.php?uniqueParamVal=' + new Date().getTime(), true);
xhr.send(formData);
};
控制台显示:
DING!1
[{"name":"1452525771.jpg","file":"..\/folder_with_images\/1452525771.jpg"}]
typeof this.responseText是字符串。
它们都位于同一个域中
错误:&#34;意外的令牌&#34;,没有令牌显示...
我的代码有问题吗?如果是这样,有什么可能的解决方案? 如果没有,我可以用什么来获得我想要的相同结果?
TL; DR:
Javascript在JSON.parse(this.responseText)
中XMLHttpRequest.onload
停止
typeof this.responseText是字符串。
它们都位于同一个域中
错误:&#34;意外的令牌&#34;,没有令牌显示...
修改
我已经阅读了给出的答案,但它仍然无效。
- JSON.parse()
只能接受字符串。
=typeof this.responseText
是字符串。
JSON.stringify(this.response);
也不起作用。
- 新行字符,制表符和反斜杠使其无效 我通过验证器运行我的JSON字符串,它是有效的JSON。但可以肯定的是,我已经删除了所有反斜杠。实际上,我已经注释掉了一些PHP。
if (move_uploaded_file($_FILES["files"]["tmp_name"][$position], $target_file)) {
$uploaded[] = array(
'name' => time().".".$imageFileType//,
//'file' => $target_file
);
}
返回:[{"name":"1452529278.jpg"}]
但它仍然包含一个意外的令牌。
答案 0 :(得分:0)
感谢@apsillers,我找到了答案。我把我的url_to_upload_images.php保存为UTF 8,用bom。这会在返回JSON时创建一个不可见的字符。
将文件保存为没有BOM的UTF 8,它可以正常工作!