doulu8537 2014-08-06 13:42
浏览 52
已采纳

如何获得从php到jquery ajax的响应

Hi I am trying to echo out certain messages from the php code back to my ajax. But normally I would only have one echo message but this case I have 2. But I have no idea on how to assign each echo to one one .html()

$("#finish").submit(function(){
    $.ajax({
        type:"GET",
        url:"checkFinish.php",
        data: $("#finishProj").serialize(),
        success: function(data){
            $("#add_sucess").html();
            $("#add_err").html();
        }
    }
});


if(!empty($mile1) && $mile1Pay == 'unPaid'){
        $error = 'Payment Not Completed';
        echo $error;
}
if(!empty($mile2) && $mile2Pay == 'unPaid'){
        $error = 'Payment Not Completed';
        echo $error;
}
if(!empty($mile3) && $mile3Pay == 'unPaid'){
        $error = 'Payment Not Completed';
        echo $error;
}

if(empty($error)){
  $success = "Success";
 echo $success;
}

I would like my echo $error to go inside the $("#add_err").html(); and echo $success to be in the $("#add_sucess").html(); How do I specify it? Cause normally if I only have one thing to echo out I would just $("#add_sucess").html(data);

  • 写回答

2条回答 默认 最新

  • duandaodao6951 2014-08-06 13:51
    关注

    I would return a JSON object back to my ajax. This way I can divide my messages up better.

    JavaScript

    $("#finish").submit(function(){
        $.ajax({
            type:"GET",
            url:"checkFinish.php",
            dataType: "JSON",//ajax now expects an JSON object to be returned
            data: $("#finishProj").serialize(),
            success: function(data){  
                //now that data is a JSON object, you can call the properties via data.prop              
                $("#add_sucess").html(data.success);
                $("#add_err").html(data.error);
            }
        }
    });
    

    PHP

    if(!empty($mile1) && $mile1Pay == 'unPaid'){
            $error = 'Payment Not Completed';
    }
    if(!empty($mile2) && $mile2Pay == 'unPaid'){
            $error = 'Payment Not Completed';
    
    }
    if(!empty($mile3) && $mile3Pay == 'unPaid'){
            $error = 'Payment Not Completed';           
    }    
    if(empty($error)){
      $success = "Success";   
    }
    
    echo json_encode(array("error" => $error, "success" => $success));//json_encode an associative array and echo it back to request
    
    exit();
    

    Just make sure you have $success and $error defined before, otherwise you'll probably get an error.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器