【发布时间】:2016-04-04 09:32:26
【问题描述】:
我一直在尝试为我正在开发的网站上传文件。我在表单之外执行此操作,经过几天的搜索,我终于从this question: 的答案中找到了适合我方法的东西@
问题是,当我将代码应用到自己的脚本时,我得到了“未定义索引”错误,当我删除它时,一切正常。
这是我的代码:
HTML
<div class='error-msg'></div>
<input type='text' id='newsitem-message' />
<input type='file' id='newsitem-thumbnail' />
<div class='submit' onclick='newsItem(\"insert\");'>Post news</div>
jQuery
function newsItem(action){
var thumbnail = $('#newsitem-thumbnail')[0].files[0];
var fileReader = new FileReader();
fileReader.readAsText(thumbnail, 'UTF-8');
fileReader.onload = shipOff;
function shipOff(e){
var r = e.target.result;
if(action == "insert"){
$.post("requestPages/newsitems.php", {message:$("#newsitem-message").val(),
thumbnail:thumbnail.name,
action:action,
data:r},
function(result){
console.log(result);
console.log(r); //This freezes my console/inspector window, forcing me to restart the browser-tab
if(result == "succes"){
window.location.reload();
}else{
$(".error-msg").html(result);
}
});
}else if(action == "delete"){
//To be implemented when I get the submit working D:
}
}
}
PHP(请见谅——需要认真清理)
<?php
include("../assets/libs/SQLLib.php");
DB_Connect("test");
echo print_r($_POST);
echo var_dump($_POST);
$message = $_POST['message'];
$action = $_POST['action'];
$thumbnail = $_POST['thumbnail'];
$data = $_POST['data'];
$serverFile = time().$thumbnail;
$fp = fopen('../assets/images/thumbnails/'.$serverFile, 'w');
fwrite($fp, $data);
fclose($fp);
$returnData = array("serverFile" => $serverFile);
echo json_encode($returnData);
if($_POST['message'] != ""){
$canPost = true;
}else{
echo "The message can not be empty.";
}
if($action == "insert" && $canPost){
$sql = "insert into newsitems
(date, message, thumbnail)
values
(NOW(),'".$message."', '".$thumbnail."')";
$result = mysql_query($sql);
if(!$result){
echo "Uh-oh! Something went wrong while posting the news! ".mysql_error();
}else{
echo "succes";
}
}else if($action == "delete"){
$sql = "";
}
?>
有人知道这里出了什么问题吗?或者有人有其他选择吗?
希望有人能帮我解决这个问题。
【问题讨论】:
-
console.log(result);先检查值,然后检查print_r($_POST);的结果是什么 -
感谢@devpro 的快速回答在将 console.log() 添加到我的代码时,我注意到我有一个双重声明的变量,但甚至重命名了这两个变量之一没有解决任何问题。我已经更新了上面的代码,使用 console.log() 调用 - 一个转储我的错误消息,另一个冻结我的检查器视图。
-
您到底得到了哪些“未定义索引”错误?我无法重现任何此类错误。
-
@ImClarky PHP 错误如 Notice: Undefined index: message 之类的。仅当我未注释文件上传代码时才会发生这种情况。当我对这些文章发表评论时(基本上是后期操作,但没有缩略图),一切正常,新闻项目被放入数据库中。
-
@ImClarky 这是全屏图片:dropbox.com/s/pz3sy21jfq2cioq/PHP_Errors.png?dl=0
标签: javascript php jquery jquery-file-upload