【问题标题】:jquery form plugins json not working as it shouldjquery表单插件json不能正常工作
【发布时间】:2012-12-06 10:54:44
【问题描述】:

我正在使用 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"]) 时会出现未定义?我希望得到 true 或 false 以及 .imgContainer 的值

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

【问题讨论】:

    标签: jquery jquery-forms-plugin jqueryform


    【解决方案1】:

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

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

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

    【讨论】:

    • 感谢您帮助我。事情进展顺利:而不是完成:
    猜你喜欢
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 2016-07-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多