我想通過ajax提交數據並輸入到數據庫。但是,我能得到它的唯一方法是如果它重定向到PHP文件。我嘗試過使用e.preventDefault();
,e.stopImmediatePropagation();
和return false;
,但沒有任何效果。我最終在表單提交時運行該函數,它從PHP文件中獲取答案,但沒有輸入到數據庫中。e.preventDefault()不工作,返回false並嘗試更多
這是我的代碼工作(但加載PHP頁面):
function uploadImage(e) {
e.preventDefault();
e.stopImmediatePropagation();
var input = document.getElementById("images"),
date = document.getElementById("image_date").value,
formdata = new FormData();
$.ajax({
url: "submit_image.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
hideImageUpload();
removeAllPosts();
getAllPosts();
}
});
return false;
}
這裏是行不通的代碼,但得到的迴應:
$('#image_upload_form').on('submit', function uploadImage(e) {
var input = document.getElementById("images"),
date = document.getElementById("image_date").value,
formdata = new FormData();
$.ajax({
url: "submit_image.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
hideImageUpload();
removeAllPosts();
getAllPosts();
}
});
e.preventDefault();
e.stopImmediatePropagation();
return false;
});
,這裏是的PHP:
<?php
require_once 'core/init.php';
$user = new User();
$errors = $_FILES["images"]["error"];
$date = $_POST['image_date'];
$d = explode("/", $date);
$nd = $d[2] . '-' . $d[0] . '-' . $d[1] . ' 00:00:00';
echo $nd;
foreach ($errors as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
//$ext = pathinfo($name, PATHINFO_EXTENSION);
$name = explode("_", $name);
$imagename='';
foreach($name as $letter){
$imagename .= $letter;
}
move_uploaded_file($_FILES["images"]["tmp_name"][$key], "images/uploads/" . $user->data()->id . '_' . $imagename);
$user->create('photos', array(
'osid' => $user->data()->id,
'user' => $user->data()->username,
'gallery' => 'Uploads',
'filename' => "images/uploads/" . $user->data()->id . '_' . $imagename,
'uploaddate' => $nd
));
$user->create('status', array(
'osid' => $user->data()->id,
'account_name' => $user->data()->username,
'author' => $user->data()->name . ' ' . $user->data()->surname,
'type' => 'image',
'data' => "images/uploads/" . $user->data()->id . '_' . $imagename,
'postdate' => $nd
));
}
}
echo "<h2>Successfully Uploaded Images</h2>";
有什麼,我失蹤?
這仍然不幸打開PHP文件 – user3185528
我添加了'return false;'並且它能夠工作,但是在附加時它說「沒有足夠的參數,所以我添加了參數:'formdata.append(」images「,$('#images'));'現在它正在使這個值'#'? – user3185528
@ user3185528我更新了代碼示例,試試。此外,我有一個錯字,應該是'$(「#response」)。html(res)' – jammykam