2012-04-11 121 views
6

好吧,我有一個PHP腳本結束像這樣:發送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"); 
       } 
    }); 

}); 

編輯源

+0

函數中調用了「return 1」語句嗎? – 2012-04-11 22:26:16

+2

_「Yea」_是什麼意思? – gdoron 2012-04-11 22:26:41

+0

您應該輸出1作爲JSON。 – 2012-04-11 22:27:43

回答

5
 <?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> 
+0

回到這個工作,我得到轉發到一個頁面,說: '{「success」:true}' 它進入一個頁面domain.com/script.php,當它不應該去那裏。 – lostAstronaut 2012-04-19 23:43:40

+0

我試圖運行你的腳本,它不起作用。如果我確實提醒(響應),我得到了{「status」:1} ...所以我想這就是它不起作用的原因。另外,如果我不刪除dataType:'json'腳本不做任何事情。 – doplumi 2013-08-24 14:03:09

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