正确使用ajax成功?

时间:2014-03-19 22:16:42

标签: javascript php jquery ajax

为什么我的成功功能永远不会运行?

的JavaScript:

$.ajax({
    url: 'calculation.php',
    type: 'POST',
    dataType: "json",
    data: {
        data1: 2,
        data2: 3
    },
    success: function(result){
        alert(result);
    }
});

PHP:

if(isset($_POST["data1"])){
    $dataA = $_POST["data1"];
    $dataB = $_POST["data2"];
    if(dataA + dataB === 5){
        echo "success";
        $result = true; //I tried all 3 of these things which it seemed like others did but it still dosen't run.
        return $result;
    }
}

2 个答案:

答案 0 :(得分:2)

尝试

echo json_encode("success");

您已将数据类型设置为json,因此您必须返回json。

答案 1 :(得分:0)

试试这个。

JavaScript代码:

$.ajax({
    type: "POST",
    url: "calculation.php",
    data: sendData,
    success: function(data) {

        var announcement = JSON.parse(data).announcement;

        alert(announcement);
    },
    error: function(data) {
        alert("AJAX error");
        console.log(data);
    }
});

PHP代码:

//Response to be sent back as json object
$response = array(
    "announcement" => "This is where you put what you want to be returned."
);

echo json_encode($response);

我想添加announcement部分,因为如果PHP出现错误,PHP错误将不会直接显示给用户。尝试调用JSON.parse(data).announcement时,JavaScript会失败。