我正在创建一个简单的上传脚本。我使用一个简单的表单让人们上传图片,然后外部 php 脚本将上传图片并将一些变量返回到上传页面。
但我无法让部分变量返回工作。目前我正在使用这个:
还包含表单的页面:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
应该返回一些数据的上传页面:
echo json_encode(array('naam'=>$naam));
此脚本返回未定义..
如果我在表单页面上响应后删除['naam'],它将打印出来: {“naam”:“test.png”}
希望有人知道我做错了什么。 提前致谢!
最佳答案
你说:
dataType: 'text', // what to expect back from the PHP script, if anything
...所以 jQuery 将忽略服务器声明的数据是什么(这似乎是 HTML,因为您没有更改 PHP 中的 Content-Type header )并像处理纯文本一样处理响应。
response
因此将是纯文本字符串,而不是解析 JSON 的结果。
将dataType
更改为“json”
。
关于javascript - json_encode 将数据发送回js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29769930/