我正在尝试通过formdata将图像通过AJAX发送到我的API,然后传递给几个函数来创建图像帖子。然而,PHP抛出了一个未识别的索引错误......我无法理解为什么。
我用这个生成了我的formdata
var fd = new FormData();
var files = $('#FileInput')[0].files[0];
var user = <?php echo $user_id; ?>;
var bodytext = $("#PostBox").val();
fd.append('file', files);
fd.append('user_id', user);
fd.append('body', bodytext);
然后,通过AJAX发送...
$.ajax({
type: "POST",
url: "api/createimgpost",
processData: false,
contentType: "application/json",
data: fd,
success: function(r) {
console.log(r)
//location.reload();
},
error: function(r) {
console.log(r)
});
然后通过PHP进行撤消,将数据传递给我的函数...
else if ($_GET['url'] == "createimgpost")
{
$user_id = Login::isLoggedIn();
$poster_id = $_POST['user_id'];
if ($user_id == $poster_id)
{
$body = isSet($_POST['body']);
$imgForm = isSet($_FILES['file']);
$img = Images::Upload($imgForm);
Post::CreateImgPost($img, $body, $user_id);
}
}
在我的网络选项卡中,看起来表格被发送得很好......
------WebKitFormBoundarybBk6iZXXDNWy6L3K
Content-Disposition: form-data; name="file"; filename="DefaultHeader.png"
Content-Type: image/png
------WebKitFormBoundarybBk6iZXXDNWy6L3K
Content-Disposition: form-data; name="user_id"
1
------WebKitFormBoundarybBk6iZXXDNWy6L3K
Content-Disposition: form-data; name="body"
asdasdasdasd
------WebKitFormBoundarybBk6iZXXDNWy6L3K--
但我仍然在user_id上得到一个未识别的索引错误(我也假设正文和文件)。我错过了一些简单的事吗?还是有点像诺贝尔......
将你的contentType:
更新为contentType: false,
也
您的检查应该类似于:
if( ! isset( $_GET['url'] ) ){ // if $_GET['url'] is not set
echo 'No URL Set';
die();
}
if ($_GET['url'] == "createimgpost"){
if( ! isset( $_POST['user_id'] ) ){ // if $_POST['user_id'] is not set
echo 'No User ID Set';
die();
}
$user_id = Login::isLoggedIn();
if ( $user_id != $_POST['user_id'] ){
echo 'No User ID Doesnt Match';
die();
}
if( ! isset( $_POST['body'] ) ){ // if $_POST['body'] is not set
echo 'No Body Set';
die();
}
if( ! isset( $_FILES['file'] ) ){ // if $_FILES['file'] is not set
echo 'File Not Set';
die();
}
if( $_FILES['file']['error'] !==0 ){ // if $_FILES['file'] has errors
echo $_FILES['file']['error'];
die();
}
$img = Images::Upload( $_FILES['file'] );
Post::CreateImgPost( $img , $_POST['body'] , $user_id );
//run checks on your POST creation. Whatever it returns for success
echo 'Success';
die();
}