0

因此,我一直在尝试将我的网站从仅使用 PHP 和 HTML 上传带有和不带图像的状态更新转换为使用 PHP、AJAX 和 HTML,因此它不必加载全新的页面即可成功更新数据库等它进展顺利,直到我不得不上传图片。

我的 JavaScript/jQuery/AJAX 代码如下所示:

$(function() {  
$("#statusupdate").on('submit', function (e) {  
    var category = $("#statusupdate input[type=radio]:checked").val();
var text = $("textarea#statusupdate_text").val();
var file = $("input#file").val();
$.ajax({  
type: "POST",  
url: "snippets/post_statusupdatequery.php",  
data: { category : category, text : text, file : file },  
success: function() {  
$('#statusupdate').html("<div id='success_status'></div>");  
$('#success_status').html("<h2>Post Submitted!</h2>")  
.append("<p>We will be in touch soon.</p>")  
.hide();  
}  
});
    return false;  
e.preventDefault();
});  
});

http://pastebin.com/fSGFa32D 我的 PHP 代码如下所示:

if (!empty($_FILES['userfile'])) {
$raw_text = $_POST['text'];
$text = mysql_real_escape_string($raw_text);
$uploaddir = '/var/www/images/imageupdate/';
$filename = "".$id."-".$time."";
$uploadfilenam = basename($filename);
$uploadfilename = $uploadfilenam.".png";
$uploadfile = $uploaddir.$uploadfilename;

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
mysql_query("INSERT INTO imagepost
    (userid, text, image, date)
    VALUES('$id', '$text', '$uploadfilename', '$time') ") or die(mysql_error());
             }
 } else {
    echo '<script>alert(" Select a file to upload! ");</script>';
  }

http://pastebin.com/6Yam6Mtd

目前据我所知,它在 PHP 代码中的第一个 if 语句上失败了,我在 stackoverflow 上进行了谷歌搜索,但我找不到与此类似的问题。

所以请帮忙,我错过了什么让文件“通过AJAX发送”到PHP?

4

1 回答 1

0

you can't upload a file using this javascript syntax

var file = $("input#file").val();

use the jquery ajax form to submit forms with file elements in it. also ensure the form has a enctype=multipart/form-data

To get ajax form to work first you setup your html form

<form id="myform" ...>.........</form>

Then you can have the jquery code attached to the form submit event by simply doing

$('#myform').ajaxForm(); //you can pass the same options as you would pass to $.ajax(); 
于 2013-07-10T01:56:26.493 回答