发送php响应给ajax

时间:2012-04-11 22:24:53

标签: php jquery ajax return

好的,我有一个php脚本,结尾如此:

if ($success)
{
    $result = array('success' => true);
}
else
{
    $result = array('success' => false, 'message' => 'Something happened');
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}
  echo json_encode($result);

当我的脚本工作时,我计划提醒我一些jquery。

    jQuery(document).ready(function() {

    $.ajax({
        url: './contactengine.php',
        type: 'GET',
        dataType: 'JSON',
        success: function(response) {
                        alert("GOOD");
                },
                error: function() {
                        alert("BAD");
                }
    });

});

已编辑的来源

2 个答案:

答案 0 :(得分:6)

        <?php 
        if ($success){
             $result = array("status" => "1");

             echo json_encode($result);
            }
            else{
              print "<meta http-equiv=\"refresh\" content=\"0;URL=/404.html\">";
            }    
        ?>
        <script>
        jQuery(document).ready(function() {

          $.ajax({
                           type: 'GET',
                           url:  'Thatscriptsomething.php',
                           cache: 'false',
                           dataType: 'json',
                           success: function(response) {
                               if(response.status == "1") {
                                    alert("we having a working script");
                               } else {
                                    alert("Oops, script is a no go");
                               }
                            }
                        });
        });
        </script>

答案 1 :(得分:4)

基本示例 - 它适用于我

PHP回复

$value =  array('msg' => 'true' );
          echo json_encode($value);

AJAX方法

 $.ajax({  
  type: 'post',  
  url: 'URL',  
  contentType: false,
  processData: false,
  dataType:'JSON',
  data: formData,
      success: function(value) {
                if (value.msg ==  'true') {
                      //your action
                }else{
                      //your action
                }
      }
});