使用ajax不返回JSON对象

时间:2012-06-04 22:39:36

标签: php jquery ajax json

我开始玩JSON了,我一直遇到麻烦,Google和SO都没有帮助我。我有一个非常简单的PHP脚本:

<?php

$email = $_REQUEST['email'];

if ( strpos($email,'@') !== false ) {
    $data = array('status' => 1 , 'msg' => 'Sent') ;
    echo json_encode( $data ) ;
} 

else {
    $data = array('status' => 0 , 'msg' => 'Failed to send') ;
    echo json_encode( $data ) ; 
}


?>

我有以下ajax调用:

$('.submit').click(function() {
    $('div.load').html('<img src="images/load.gif" alt="Loading..." id="loading" />'); //EDIT

    //creation of variables to send
    var name = $('#name').val();
        email = $('#email').val();
        phone = $('#phone').val();

    $.ajax({
        type: "POST",
        dataType: "jason",

        data: {
            name: name,
            email: email,
            phone: phone
        },

        url: "test.php",

        success: function( data ) {

            $('.contact').append( data )

        }
    });

    return false; 

});

如果没有JS调用php(并且表单不包含正确的电子邮件地址),那么我得到以下对象(这就是我想要的!):{“status”:0,“msg”: “发送失败”}

但是,如果使用JS(ajax)提交,则永远不会收到JSON对象。有什么想法吗?

谢谢!

1 个答案:

答案 0 :(得分:3)

dataType: "jason",

读:

dataType: "json",

- )

另外,你有一些半冒号应该有逗号:

var name = $('#name').val(),    // These two lines should be comma-terminated to
    email = $('#email').val(),  // make this a correct var declaration
    phone = $('#phone').val();