dongmubei7950 2011-08-24 21:12
浏览 103
已采纳

AJAX JSON + PHP JSON错误

I've got a jQuery AJAX code, which recieves JSON-type data from php file. Wihout dataType: "json" everything is ok. But I need JSON-type data. Text recieved is a valid JSON code

{"ok":"false","answer":"All fields must be filled"}

But when I user dataType, I've got an error

Object "parsererror" SyntaxError

Here's JS code:

    $.ajax({
        url : "testing/regtest.php",
        type : "POST",
        dataType: "json",
        data : {
            mail : $('#mail_field').val(),
            username : $('#username_field').val(),
            password : $('#password_field').val(),
            password_2 : $('#rep_password_field').val()
        },
        success : function(data) {
            console.log(data.ok);
        },
        error: function(a,b,c) { console.log(a,b,c); }
    });

Thanks for any help!
Update: Here's php server-side code: http://jsfiddle.net/VfQbz/1/
Update 2: It works in IE9 but doesn't work in chrome

  • 写回答

3条回答 默认 最新

  • dongpengyu1363 2011-08-24 21:47
    关注

    I'm not quite sure if this works, but IMHO the problem is PHP's lousy JSON encoding function. Try:

    if (check_post() === true) {
        $password = $_POST['password'];
        $password2 = $_POST['password_2'];
        $username = $_POST['username'];
        $mail = $_POST['mail'];
        if (valid_data($password, $password2, $username, $mail) === true){
            $answer = json_encode(array("ok" => "true", "answer" =>     $service_messages["account_registered"]));
            echo "'".$answer."'"; // Note the additional single quotes
        }
    }
    

    By digging into the jQuery source I found the error to occur in the response parsing. Hope it works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3