在Jquery中将多个错误作为数组输出为JSON编码

时间:2018-03-26 05:20:47

标签: php jquery html arrays json

我将从JSON格式的PHP文件中输出多个错误作为数组输出到Jquery时遇到了麻烦。

通常,来自PHP的数据可以编码为JSON,然后发送到Jquery,以便将代码输出为Ajax成功或错误响应。到目前为止工作正常至少success:function(data),因为数据是在error:function()获取的,而不是undefined。我把相同的(数据)放在那个函数中,但没有任何回报。

为什么?我得到的是最后的回复<div class="container" style="width:700px;"> <div id="message"></div> <label>Select Image</label> <input type="file" name="file" id="file" /> <br /> <img src="upload/no-image.png" id="uploaded_image" style="height: 256px; width: auto;" class="img-thumbnail"> </div> 。我甚至都不知道这是否是正确的方法。顺便说一句,在PHP代码中,可能有很多错误输出全部存储或堆叠为数组。实际上无所谓。

HTML:

$(document).ready(function () {
    $(document).on('change', '#file', function () {
        formdata.append("file", document.getElementById('file').files[0]);
        $.ajax({
            url: "upload.php",
            method: "POST",
            data: formdata,
            dataType: 'json',
            contentType: false,
            cache: false,
            processData: false,
            beforeSend: function () {
                $('#uploaded_image').html("<label class='text-success'>Image Uploading...</label>");
            },
            success: function (data) {
                $('#message').addClass('alert alert-success').html(data.reply);
                alert(data.reply);
                $('#uploaded_image').attr('src', data.imgURL);
            },
            error: function (data) {
                // $('#message').html(data.err);
                alert(data.err);
            }
        });
    });
});

JQUERY:

<?php
$err = array();

if ($_FILES["file"]["name"] != '') {
    // $test = explode('.', $_FILES["file"]["name"]);
    // $ext = end($test);

    $uploadDir = "upload/";
    $name = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME);
    $extension = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    $targetpath = $uploadDir . $name . '.' . $extension;

    if (file_exists($targetpath)) {
        $err[] = 'Sorry, file exists and cannot be processed';
        die;
    }

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetpath)) {

        $response = array('imgURL' => $targetpath, 'reply' => 'Image uploaded successfully');
        echo json_encode($response);

        // echo '<img src="'.$targetpath.'" height="150" width="225" class="img-thumbnail" />';
    } else {

        $err[] = 'Nope, something went wrong';
        echo json_encode($err);

        // $error = array('err' => 'Nope, something went wrong');
        // echo json_encode($error);
    }
}
?>

PHP:

catch (e) {
      var $content = $(xhr.responseText).remove('style');
      $("#dialog").empty().append($content);
}

2 个答案:

答案 0 :(得分:0)

MD5

JS

<?php
$err = array();

if ($_FILES["file"]["name"] != '') {
    // $test = explode('.', $_FILES["file"]["name"]);
    // $ext = end($test);

    $uploadDir = "upload/";
    $name = pathinfo($_FILES['file']['name'], PATHINFO_FILENAME);
    $extension = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
    $targetpath = $uploadDir . $name . '.' . $extension;

    if (file_exists($targetpath)) {
        $err[] = 'Sorry, file exists and cannot be processed';
        die;
    }

    if (move_uploaded_file($_FILES["file"]["tmp_name"], $targetpath)) {

        $response = array('imgURL' => $targetpath, 'reply' => 'Image uploaded successfully');
        echo json_encode(array("status"=>true,"response"=>$response));

        // echo '<img src="'.$targetpath.'" height="150" width="225" class="img-thumbnail" />';
    } else {

        $err[] = 'Nope, something went wrong';
        echo json_encode(array("status"=>false,"error"=>$err));

        // $error = array('err' => 'Nope, something went wrong');
        // echo json_encode($error);
    }
}
?>

您可以从PHP发送状态为true,如果响应错误,请检入JS。如果它的错误只是循环遍历它并使用JS中的success: function (data) { if(data.status){ $('#message').addClass('alert alert-success').html(data.response.reply); alert(data.response.reply); $('#uploaded_image').attr('src', data.response.imgURL); }else{ $.each(data.error, function(k, v){ alert(v); }); } }, 在HTML中显示您的错误。

答案 1 :(得分:0)

当服务器正确响应并且不会抛出错误时调用AJAX成功函数,否则调用错误函数。因此,当您成功发送JSON编码值时,该过程是正确的,因此将调用成功函数而不是错误函数。

因此,当您发送$ err时,将在流程成功完成时调用success函数。从逻辑上讲,您正在发送错误,但对于jquery,重要的是AJAX是否成功完成。只需检查您的JSON对象,看看您是否有错误obj。

修改你的PHP

$err = array(errMsg => "Nope, something went wrong");

修改JS成功函数

        success: function (data) {
            if (data.errMsg != "")
            {
                 //Handle error
            }
            else
            {  
                $('#message').addClass('alert alert-success').html(data.reply);              
                alert(data.reply);
                $('#uploaded_image').attr('src', data.imgURL);
            }
        },
相关问题