weixin_33696106
weixin_33696106
2014-03-19 22:16
采纳率: 0%
浏览 18

正确使用Ajax成功吗?

Why does my success function never runs?

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;
    }
}

图片转代码服务由CSDN问答提供 功能建议

                    

为什么我的成功功能永远无法运行?

JavaScript:
  $。ajax({
     网址:“ calculation.php”,
     输入:“ POST”,
     dataType:“ json”,
     数据:{
         数据1:2
         数据2:3
     },
     成功:功能(结果){
         警报(结果);
     }
 });
  

 

PHP:
  if(isset($ _ POST [“ data1”])){
     $ dataA = $ _POST [“ data1”];
     $ dataB = $ _POST [“ data2”];
     if(dataA + dataB === 5){
         回声“成功”;
         $ result = true;  //我尝试了所有这3件事,就像其他人一样,但仍然无法运行。
         返回$ result;
     }
 }
  
     

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • weixin_33676492
    weixin_33676492 2014-03-19 22:18

    Try

    echo json_encode("success");
    

    You have set the data type to json so you have to return json.

    点赞 评论
  • weixin_33726313
    weixin_33726313 2014-03-19 22:37

    Try this.

    JavaScript Code:

    $.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 Code:

    //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);
    

    I like to add the announcement part because if something with PHP goes wrong, a PHP error won't be displayed directly to the user. JavaScript will fail when it tried to call JSON.parse(data).announcement.

    点赞 评论

相关推荐