0

我正在尝试使用从服务器发送的 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>

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

4

1 回答 1

1

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

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

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

于 2012-12-04T13:32:11.843 回答