문제

I'm using the jquery form plugin to upload an Image, and everything goes on well. The problem I'm having is when it comes to the json response sent by the php script from the server.

//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?

I'm using 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"]);


                }
            });
        }

    });

Why do I get undefined when I try to access (xhr.responseText["success"])? I was hoping to get true or false and the value of the .imgContainer

Maybe its not interpreting it as json. How can I solve this?

도움이 되었습니까?

해결책

You will have to use success instead of complete. In complete you can only access the raw JSON string and you'd have to parse it before you can access it as an object.

In success the parameter will have the JSON object (not the string) so you could directly access it.

success: function(data) {
   console.log(data.success);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top