dongxu4023 2013-11-25 22:38
浏览 127
已采纳

jquery.ajax json错了吗?

hey i have a problem submitting my data via jquery and back:

$.ajax({
    url: "checkAvailability.php",
    type: 'POST',
    data : {data:JSON.stringify(data)},
    success: function(data) {
        if (data.result == 0) {
            alert("0")
        } 
        if(data.result == 1) {
            alert("1")
        }
    }
});

so, ONE of those if-conditions must be true, because of:

checkAvailability.php:

if(isset($_POST['data'])) {
    define('SECURE', true);
    include "storescripts/connect_to_mysql.php";

    require 'AvailabilityChecker.php';

$config = array(etc..);

    $availabilityChecker = new AvailabilityChecker($config);

    $data = $_POST['data'];
    $data = json_decode($data,true);

    preg_match( '/(\d+(\.\d+)?)/', $data['x'] , $m);
    $x =  $m[0];

    if($availabilityChecker->check_availability($x)) {
        echo json_encode(array("error" => "is ok", "result"=>1));
    } else {
        echo json_encode(array("error" => "not ok", "result"=>0));
    }
}

data.result have to be 1 OR 0. anybody can tell me why there is no alert-message? greetings!

UPDATE:

$.ajax({
    url: "checkAvailability.php",
    type: 'POST',
    data : {data:JSON.stringify(data)},
    success: function(data) {
        if (data.result == 0) {
            alert("0")
        } else { alert("fail-1") }
        if(data.result == 1) {
            alert("1")
        } else { alert("fail-2") }
    }
});

now i get first the fail-1 alert and than the fail-2 alert, so both if-conditions are false, why?

  • 写回答

3条回答 默认 最新

  • duandong2562 2013-11-25 22:53
    关注

    You need to specify the dataType, otherwise jquery will instead try to guess what you are trying to do. In this case it is incorrectly guessing text/html rather than application/json.

    $.ajax({
        url: "checkAvailability.php",
        type: 'POST',
        dataType: 'json',
        data : {data:JSON.stringify(data)},
        success: function(data) {
            if (data.result == 0) {
                alert("0")
            } else { alert("fail-1") }
            if(data.result == 1) {
                alert("1")
            } else { alert("fail-2") }
        }
    });
    

    You should also properly set the content-type header in php, before you echo the json.

    header('Content-type: application/json');
    

    You can get away with doing either-or, but i'd suggest doing both.

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集