1

我正在使用 jquery 表单插件上传图片,一切顺利。我遇到的问题是关于 php 脚本从服务器发送的 json 响应。

//This is the way i output and encode the jason in my php script
$errors['success'] = false;
$errors['.imgContainer'] = 'Image exceeds maximum size.';
echo json_encode($errors);


//Json response copied from console in FireFox 14.0.1
{"success":false,".imgContainer":"Image exceeds maximum size."}


//Console response for:
console.log(xhr.responseText["success"]);
Undefined
//This should have been true right?

我正在使用 jquery 1.8.0

//My Jquery
$('.imageForm').live('click', function(e) {
        if (!isValid) {
            e.preventDefault();
        }
        else {
            var bar = $('.bar');
            var percent = $('.percent');
            var response = $('.imgHolder');
            var status = $('#status');

            $('form').ajaxForm({
                contentType : "application/json; charset = utf-8",
                dataType: "json",
                type    : "POST",
                url     : "imgHandle.php",
                cache : false,


                //target: "#status",

                beforeSend: function() {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                    $(".imgContainer :input").attr("disabled", true);
                },
                uploadProgress: function(event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function(xhr) {

                    console.log(xhr.responseText["success"]);


                }
            });
        }

    });

为什么我在尝试访问 (xhr.responseText["success"]) 时会出现未定义?我希望得到真或假以及 .imgContainer 的值

也许它没有将其解释为 json。我该如何解决这个问题?

4

1 回答 1

3

您将不得不使用success而不是complete. complete您只能访问原始 JSON 字符串,并且必须先对其进行解析,然后才能将其作为对象访问。

success参数中将包含 JSON 对象(不是字符串),因此您可以直接访问它。

success: function(data) {
   console.log(data.success);
}
于 2012-12-06T11:00:57.063 回答