2012-03-12 42 views
57

我不斷收到錯誤警報。 MYSQL部分沒有錯,查詢得到執行,我可以在數據庫中看到電子郵件地址。如何使用PHP爲JQuery .ajax()返回正確的成功/錯誤消息?

客戶端:

<script type="text/javascript"> 
    $(function() { 
    $("form#subsribe_form").submit(function() { 
     var email = $("#email").val(); 

     $.ajax({ 
     url: "subscribe.php", 
     type: "POST", 
     data: {email: email}, 
     dataType: "json", 
     success: function() { 
      alert("Thank you for subscribing!"); 
     }, 
     error: function() { 
      alert("There was an error. Try again please!"); 
     } 
     }); 
     return false; 
    }); 
    }); 
</script> 

服務器端:

<?php 
$user="username"; 
$password="password"; 
$database="database"; 

mysql_connect(localhost,$user,$password); 
mysql_select_db($database) or die("Unable to select database"); 

$senderEmail = isset($_POST['email']) ? preg_replace("/[^\.\-\_\@a-zA-Z0-9]/", "", $_POST['email']) : ""; 

if($senderEmail != "") 
    $query = "INSERT INTO participants VALUES (CURDATE(),'".$senderEmail."')"; 
mysql_query($query); 
mysql_close(); 

$response_array['status'] = 'success';  

echo json_encode($response_array); 
?> 
+6

考慮使用pdo,mysql_函數已經過時 – 2014-10-13 11:20:57

回答

103

你需要的,如果你使用JSON數據類型來提供合適的內容類型。在回顯json之前,請輸入正確的標題。

<?php  
    header('Content-type: application/json'); 
    echo json_encode($response_array); 
?> 

另外的修復,你應該檢查查詢是否成功。

if(mysql_query($query)){ 
    $response_array['status'] = 'success'; 
}else { 
    $response_array['status'] = 'error'; 
} 

在客戶端:

success: function(data) { 
    if(data.status == 'success'){ 
     alert("Thank you for subscribing!"); 
    }else if(data.status == 'error'){ 
     alert("Error on query!"); 
    } 
}, 

希望它能幫助。

+1

哦,您應該區分*服務器端錯誤*和*傳輸錯誤*。我把這個檢查放在AJAX的'success'部分來檢查服務器發送的值(所以它不是傳輸錯誤)。 – 2012-03-12 23:33:31

19

有人建議使用HTTP狀態代碼,但我寧願鄙視這種做法。例如如果你正在做一個搜索引擎,並且提供的關鍵字沒有結果,那麼建議將會返回一個404錯誤。

但是,我認爲這是錯誤的。 HTTP狀態代碼適用於實際瀏覽器< - >服務器連接。一切有關連接完美。瀏覽器發出請求,服務器調用您的處理程序腳本。該腳本返回「無行」。沒有任何內容表示「404頁面未找到」 - 發現頁面WAS

相反,我贊成將HTTP層從服務器端操作的狀態中分離出來。我總是返回一個JSON數據結構來封裝請求狀態和請求結果,而不是簡單地返回一些json字符串中的文本。

例如在PHP中你必須

$results = array(
    'error' => false, 
    'error_msg' => 'Everything A-OK', 
    'data' => array(....results of request here ...) 
); 
echo json_encode($results); 

然後在您的客戶端代碼,你就必須

if (!data.error) { 
    ... got data, do something with it ... 
} else { 
    ... invoke error handler ... 
} 
28

就這麼你知道,你可以用它來調試。它幫了我很多,並且仍然沒有

error:function(x,e) { 
    if (x.status==0) { 
     alert('You are offline!!\n Please Check Your Network.'); 
    } else if(x.status==404) { 
     alert('Requested URL not found.'); 
    } else if(x.status==500) { 
     alert('Internel Server Error.'); 
    } else if(e=='parsererror') { 
     alert('Error.\nParsing JSON Request failed.'); 
    } else if(e=='timeout'){ 
     alert('Request Time out.'); 
    } else { 
     alert('Unknow Error.\n'+x.responseText); 
    } 
} 
+0

太棒了!剛發現我的服務器不支持json_encode – Pieter 2012-03-13 00:29:05

+0

@Pieter:然後實現你自己的js_encode :)試試這個:http://snippets.dzone.com/posts/show/7487 – 2012-03-13 01:38:41

+0

明白了,thx穆罕默德。 – Pieter 2012-03-13 14:34:51

0

加入頂端的答案:這裏是PHP和jQuery一些示例代碼:

$("#button").click(function() { 
$.ajax({ 
      type: "POST", 
      url: "handler.php", 
      data: dataString, 

       success: function(data) { 

        if(data.status == "success"){ 

       /* alert("Thank you for subscribing!");*/ 

        $(".title").html(""); 
        $(".message").html(data.message) 
        .hide().fadeIn(1000, function() { 
         $(".message").append(""); 
         }).delay(1000).fadeOut("fast"); 

       /* setTimeout(function() { 
         window.location.href = "myhome.php"; 
        }, 2500);*/ 


        } 
        else if(data.status == "error"){ 
         alert("Error on query!"); 
        } 




        } 


     }); 

     return false; 
    } 
}); 

PHP - 發送自定義消息/狀態:

$response_array['status'] = 'success'; /* match error string in jquery if/else */ 
    $response_array['message'] = 'RFQ Sent!'; /* add custom message */ 
    header('Content-type: application/json'); 
    echo json_encode($response_array); 
1

爲了建立一個AJAX的web服務,你需要兩個文件:

  • 主叫的Javascript發送數據作爲POST使用JQuery AJAX
  • 甲PHP web服務返回JSON對象(這是方便的返回陣列或大量數據)

所以(可能是作爲GET)首先調用使用這個jQuery的語法你的web服務,JavaScript文件中:

$.ajax({ 
    url : 'mywebservice.php', 
    type : 'POST', 
    data : 'records_to_export=' + selected_ids, // On fait passer nos variables, exactement comme en GET, au script more_com.php 
    dataType : 'json', 
    success: function (data) { 
      alert("The file is "+data.fichierZIP); 
    }, 
    error: function(data) { 
      //console.log(data); 
      var responseText=JSON.parse(data.responseText); 
      alert("Error(s) while building the ZIP file:\n"+responseText.messages); 
    } 
}); 

你的PHP文件(mywebservice.php,寫在AJAX調用)應包括這樣的事情在其結束,返回一個正確成功或錯誤狀態:

<?php 
    //... 
    //I am processing the data that the calling Javascript just ordered (it is in the $_POST). In this example (details not shown), I built a ZIP file and have its filename in variable "$filename" 
    //$errors is a string that may contain an error message while preparing the ZIP file 
    //In the end, I check if there has been an error, and if so, I return an error object 
    //... 

    if ($errors==''){ 
     //if there is no error, the header is normal, and you return your JSON object to the calling JavaScript 
     header('Content-Type: application/json; charset=UTF-8'); 
     $result=array(); 
     $result['ZIPFILENAME'] = basename($filename); 
     print json_encode($result); 
    } else { 
     //if there is an error, you should return a special header, followed by another JSON object 
     header('HTTP/1.1 500 Internal Server Booboo'); 
     header('Content-Type: application/json; charset=UTF-8'); 
     $result=array(); 
     $result['messages'] = $errors; 
     //feel free to add other information like $result['errorcode'] 
     die(json_encode($result)); 
    } 
?>