jquery表单插件json无法正常工作



我正在使用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["成功"])时,我没有得到定义?我希望得到真或假以及.imgContainer的值

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

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

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

success: function(data) {
   console.log(data.success);
}

最新更新