我有一个用于上传文件的PHP代码,工作正常,作为最终结果,我发送了JSON响应,上传状态是我无法检索的。
上传文件(POST)后,我的回复如下:
{"html_content":"<p>File was uploaded<\/p>"}
PHP上传代码如下:
if (!is_file($targetFile)) {
move_uploaded_file($tempFile,$targetFile);
$html_content="<p>File was uploaded</p>";
}
else {
$html_content="<p>You have uploaded duplicate.</p>";
move_uploaded_file($tempFile,$targetFile);
}
$json_array=array('html_content'=>$html_content);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($json_array);
和用于显示消息的JavaScript主代码:
this.on("success", function(file,responseText) {
$.ajax({
dataType: 'json',
success: function (response) {
var htmlElement = document.createElement("div");
htmlElement.setAttribute("class","success-message");
var responseText = response.html_content;
var messageText = document.createTextNode(responseText);
htmlElement.appendChild(messageText);
file.previewTemplate.appendChild(htmlElement);
console.log(response.html_content);
}
});
});
当我从AJAX部分解开上面的JS并将变量responseText
设置为静态时,一切正常。
此外,当我不使用AJAX并输出console.log(responseText);
时,我会在控制台中看到这个:
Object {html_content: "<p>File was uploaded</p>"}
在我的案例中,我有什么想法?
答案 0 :(得分:0)
您没有向PHP服务器发送请求。指定URL参数。
$.ajax({url: "your_php_file",
dataType: 'json',
success: function (response) {
...
}
});
甚至更好:
$.getJSON( "your_php_file", function( data ) { ... });
答案 1 :(得分:0)
好的,解决了。 JavaScript代码看起来像
this.on("success", function(file,responseText) {
str = JSON.stringify(responseText);
responseMessage = $.parseJSON(str);
var htmlElement = document.createElement("div");
htmlElement.setAttribute("class","success-message");
htmlElement.innerHTML = responseMessage.html_content;
file.previewTemplate.appendChild(htmlElement);
});