jQuery ajax POST消耗返回的JSON对象

时间:2012-12-04 13:28:37

标签: jquery json

我正在尝试使用从服务器发送的JSON响应。 Firebug显示从服务器返回的JSON对象是有效的,但由于某种原因,下面的代码失败......:

<script type="text/javascript">

function isValidEmailAddress(email){
// do something ...
}

$(document).ready(function(){
    $("form").on("submit", function(e){
        if ( isValidEmailAddress($('#invite-email').val()) ) {
            // setup some local variables
            var $form = $(this),
                // let's select and cache all the fields
                $inputs = $form.find("input, select, button, textarea"),
                // serialize the data in the form
                serializedData = $form.serialize();

            // let's disable the inputs for the duration of the ajax request
            $inputs.attr("disabled", "disabled");

            // fire off the request to /form.php
            $.ajax({
                url: '<?php echo $url; ?>',
                type: "post",
                data: serializedData,
                // callback handler that will be called on success
                success: function(response, textStatus, jqXHR){
                    var is_ok = response.error_code == 0 ? true : false;  // array access also fails 
                    var msg = response.msg; // array access also fails 

                    alert(is_ok);
                    alert(msg);

                    if (is_ok){
                        $('#invite-member').text(msg);
                    }
                    else{
                        $('#error-msg').text(msg);
                        $('#error-msg').show("slow");                        
                    }
                },
                // callback handler that will be called on error
                error: function(jqXHR, textStatus, errorThrown){
                    // log the error to the console
                    console.log(
                        "The following error occured: "+
                        textStatus, errorThrown
                    );
                },
                // callback handler that will be called on completion
                // which means, either on success or error
                complete: function(){
                    // enable the inputs
                    $inputs.removeAttr("disabled");
                }
            });
        }
        else {
            $('#invite-email').val('');
        }

        return false;
    });
});

</script>

我显然做了一些愚蠢的事 - 但我似乎无法将手指放在上面。我错过了什么?

1 个答案:

答案 0 :(得分:1)

尝试在启动时设置此变量。

$.ajaxSetup({
    contentType : 'application/json',
    dataType : "json"
});

它们告诉jQUery返回数据类型必须被解释为JSON。