gpt4 book ai didi

javascript - 如何检查 ajax 响应的错误列表

转载 作者:太空宇宙 更新时间:2023-11-04 16:12:53 25 4
gpt4 key购买 nike

所以我使用 ajax 和 php 来“创建帖子”,它允许您上传图像和文本。目前我有 php 来检查帖子是否有任何内容以及是否有图像,并验证所有内容。然而问题是,当我收到响应时,我会将其添加到帖子提要中,但这使得当出现错误时,它也会将其添加到帖子提要中。我想做的是将错误附加到一个名为错误的单独 div 中。这是我的 php(我刚刚开始使用 php,如果出现问题或者可以通过更少的工作更轻松地完成,请告诉我。)

<?php
require_once('../dbconnect.php');
include_once( INCLUDES_PATH .'functions.php');

$body = $_POST["body"];
$image = 'image';
$user_id = $_SESSION['user_id'];

if( empty($_FILES[$image]['name']) ){
$has_image = 0;
}else{
$has_image = 1;
}

$postEmpty = 0;

if( empty($_FILES[$image]['name']) && empty($body) ){
$postEmpty = 1;
die();
}

// validate post

if( $postEmpty == 0 && !empty($body) ){

$cleanBody = clean_input($body);

}

// validate image (if any)

if( $has_image == 1 ){

//check if directory exist if not create it
if (!file_exists(HOME_PATH ."users/user_".$user_id)) {
mkdir(HOME_PATH ."users/user_".$user_id, 0777, true);
}
if (!file_exists(HOME_PATH ."users/user_".$user_id."/posts")) {
mkdir(HOME_PATH ."users/user_".$user_id."/posts", 0777, true);
}
//Set file upload path
$path = "../users/user_".$user_id."/posts/"; //with trailing slash
//Set max file size in bytes
$max_size = 2000000;
//Set default file extension whitelist
$whitelist_ext = array('jpeg','jpg','png','gif');
//Set default file type whitelist
$whitelist_type = array('image/jpeg', 'image/jpg', 'image/png','image/gif');

// Create an array to hold any output
$errors = array();

// Get filename
$file_info = pathinfo($_FILES[$image]['name']);
$name = $file_info['filename'];
$ext = $file_info['extension'];

//Check file has the right extension
if (!in_array($ext, $whitelist_ext)) {
$errors[] = "Invalid file Extension";
}

//Check that the file is of the right type
if (!in_array($_FILES[$image]["type"], $whitelist_type)) {
$errors[] = "Invalid file Type";
}

//Check that the file is not too big
if ($_FILES[$image]["size"] > $max_size) {
$errors[] = "File is too big";
}

//If $check image is set as true
if (!getimagesize($_FILES[$image]['tmp_name'])) {
$errors[] = "Uploaded file is not a valid image";
}

//Create full filename including path
if ($random_name) {
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());

if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}
$newname = $tmp.'.'.$ext;
} else {
$newname = $name.'.'.$ext;
}

//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}

if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
}

// if no errors:

// upload image (if any) and retrieve filename
if( $imageError == 1 ){

foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}

}else{

//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());

if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}

$newname = $tmp.'.'.$ext;

//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}

if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

$uploadSuccesfull = 1;

}else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
die();
}
}

}
}


// if no errors:

// save post (with filename if any); if it fails, delete image (if any)
if( $has_image == 1 ){

$query = "INSERT INTO posts
(user_id, body, image, has_image, date)
VALUES
('$user_id', '$body', '$newname', '$has_image', now())";

}else{

$query = "INSERT INTO posts
(user_id, body, has_image, date)
VALUES
('$user_id', '$body', '$has_image', now())";

}

$result = $db->query($query);

// send response

//check to make sure the user was added
if( $db->affected_rows == 1 ){

$user_id = $_SESSION['user_id'];

$post_id = $db->insert_id;

$query = "SELECT post_id, body, image, has_image
FROM posts
WHERE post_id = $post_id
LIMIT 1";
$result = $db->query($query);

if($result->num_rows == 1){
$row = $result->fetch_assoc();
}

$queryuser = "SELECT *
FROM users
WHERE user_id = $user_id
LIMIT 1";
$resultuser = $db->query($queryuser);
if($resultuser->num_rows == 1){
$rowuser = $resultuser->fetch_assoc();
}


if(!empty($row['avatar'])){ $userpic = $row['avatar']; }else{ $userpic = HOME_URL . 'img/avatar.jpg'; }

if($row['has_image'] == 1){

?>
<article class="post">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username']; ?>
</a>
</div>
<img src="users/user_<?php echo $rowuser['user_id'] ?>/posts/<?php echo $row['image']; ?>" alt="">
<div class="post-body">
<div class="post-options">
<a class="likes" href="">156 likes</a>
</div>
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>
<?php }else{ ?>

<article class="post no-img">
<div class="post-head cf">
<a class="userpic" href=""><img src="<?php echo $userpic ?>" alt="<?php echo $rowuser['username'] ?>"></a>
<a href="" class="username">
<?php echo $rowuser['username'] ?>
</a>
</div>
<div class="post-body">
<p>
<a class="username" href="">
<?php echo $rowuser['username'] ?>
</a>
<?php echo $row['body'] ?>
</p>
<div class="post-options">
<a class="likes" href="">1 like</a>
</div>
<hr />
<div class="cf">
<a class="like hide-text" href="javascript:;">Like This Post</a>
<form action="" class="comment">
<input type="text" placeholder="Add a comment">
</form>
</div>
</div>
</article>

<?php }
}else{

echo 'There was a database error';

}

die();

这是我的 ajax 调用

$.ajax({
type: "post",
url: "includes/create-post.php",
data: new FormData(this),
processData: false,
contentType: false,
error: function (response) {
console.log(response);
},
success: function (response) {

$('section.feed').prepend(response);

$('article.post p').each(function () {
$(this).html(linkHashtags($(this).html()));
});

$('article.post p').each(function () {
$(this).html(linkatsymbols($(this).html()));
});
revealPosts();

}
});

最佳答案

对于die(),您可以简单地将语句die放在foreach之外,如下所示:

if( $imageError == 1 ){
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
.
.
.
.
.
.
if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

$uploadSuccesfull = 1;

}
else {
$errors[] = "Server Error!";
foreach($errors as $error) {
echo '<li>'.$error.'</li>';
}
die();
}

但是由于您想在其他元素中显示错误,因此您需要一种方法来检查您收到的输出是否有错误。因此,尝试用以下代码替换您的代码:

// if no errors:

// upload image (if any) and retrieve filename
if( $imageError == 1 ){

$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);

die();
}
else{

//Create full filename including path
// Generate random filename
$tmp = str_replace(array('.',' '), array('',''), microtime());

if (!$tmp || $tmp == '') {
$errors[] = "File must have a name";
}

$newname = $tmp.'.'.$ext;

//Check if file already exists on server
if (file_exists($path.$newname)) {
$errors[] = "A file with this name already exists";
}

if (count($errors)>0) {
//The file has not correctly validated
$imageError = 1;

$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);

die();
}
if (move_uploaded_file($_FILES[$image]['tmp_name'], $path.$newname)) {

$uploadSuccesfull = 1;

}
else {
$errors[] = "Server Error!";

$ret_data = ['items' => $errors, 'responseCode' => 0];
//content in $items must be in UTF-8
echo json_encode($ret_data);

die();
}

}
}

并在 AJAX 成功调用中执行如下操作:

success: function (response) {
var obj = JSON.parse(response);
var errorCode = obj.responseCode;
var errorSet = obj.items;
if(errorCode == 0) {
$.each(errorSet, function(i, v) {
console.log('<li>'+v+'</li>');
}
}
//Your rest of the code

顺便说一句,如果将代码与设计分开会更好。

关于javascript - 如何检查 ajax 响应的错误列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41326581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com