PHP ajax请求返回字符串

时间:2013-02-04 03:12:15

标签: php jquery

我在ajax请求中收到错误200。我想在我的ajax请求中将1个值作为电子邮件地址发布到页面。有人能告诉我出了什么问题

错误:

message=:[object Object], text status=:parsererror, error thrown:=SyntaxError: JSON.parse: unexpected end of data

JQuery的

$('#checkemail').click(function() {
    $.ajax({
        url:'http://' +  location.host + '/buyme/include/getemailaddress.php',
        type:'POST',
        contentType: "application/json; charset=utf-8",

        data: {email:$('#email').val()},
        dataType:"json",
        success: function(msg) {
            alert(msg);
        },
        error: function(ms, textStatus, errorThrown) {
            alert(errorThrown); 
        }   
    });/**/
});

1 个答案:

答案 0 :(得分:1)

当您使用json数据类型时,来自服务器的任何返回数据必须采用该格式。

首先不要忘记发送post数据,因此请使用:

if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    $email = $_POST['email'];
    // ...

    // and SECOND return suitable data type, ie, a json coded string.
    echo json_encode($your_result);

    // where $your_result can be simple as

    // $your_result['result'] = true;
    // $your_result['result'] = false;

    // a message
    // $your_result['msg'] = 'all OK';

    // a message and and a flag
    // $your_result['msg'] = 'all OK';
    // $your_result['result'] = true;
}

所以在你的jquery回调中,你会得到这样的返回数据:

success: function(data) {
    if (data.msg != "") alert(data.msg);
    if (data.result === true) {} else {}
},