我有一個將值發送到變量$ _POST ['person_id'],$ _POST ['accident_loc'],$ _POST ['message']和$ _POST ['name' ]。如何獲得http響應代碼
該php文件插入值作爲記錄在數據庫中,我沒有任何問題。但是,當表單不向變量發送任何值時,我想返回一個錯誤。
我的意思是當我提交一個沒有任何值的表單。所以我做了一個if語句if(isset($_POST['person_id']) && isset($_POST['accident_loc']) && isset($_POST['message']) && isset($_POST['name'])){}
,如果這個語句失敗,調用函數「sendResponse()」。
現在我想要這個文件返回狀態代碼400到我的JavaScript文件,這樣我可以寫一些錯誤條件。但是當我試圖顯示狀態碼request.status
的值,它給了我0作爲它的值
下面是我的PHP文件..你能告訴我如何發送狀態碼?
<?php
//allowing access to the server which contains the following host-origin
if($_SERVER[HOST_ORIGIN]=="http:\\localhost")
header('Access-Control-Allow-Origin:http:\\http:localhost');
function sendResponse(){
header('HTTP/1.1 400 invalid request');
header('Content-type: text/html');
echo "invalid request";
}
if(isset($_POST['person_id']) && isset($_POST['accident_loc']) && isset($_POST['message']) && isset($_POST['name']))
{
//php mysql database info
require ("phpMysql_dbInfo.php");
//getting the arguments from the url
$person_id=$_POST['person_id'];
$accident_loc=$_POST['accident_loc'];
$message=$_POST['message'];
$name=$_POST['name'];
//connecting to the database
$connection= mysql_connect($local_host,$username,$password);
if(!$connection)
die(mysql_error()."</br>");
//selecting the db
$select_db= mysql_select_db($database_name);
if(!$select_db)
die(mysql_error()."</br>");
//inserting the values into the database
$query= sprintf("insert into messages_to_people(name,accident_location,message,person_id)
values('%s','%s','%s','%s')",
mysql_real_escape_string($name),
mysql_real_escape_string($accident_loc),
mysql_real_escape_string($message),
mysql_real_escape_string($person_id));
$result=mysql_query($query);
if(!$result)
echo mysql_error().'</br>';
}
else
sendResponse();
?>
UPDATE: 這裏是我的javascript
function downloadXml (url,params,callback) {
var request= window.XMLHttpRequest ? new XMLHttpRequest(): new ActiveXObject('Microsoft.XMLHTTP');
request.onreadystatechange= function(){
if(request.readyState==4){
//gives me a zero when i try to display it through alert
alert(request.status);
callback(request, request.status);
}
};
request.open('POST',url,true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(params);
}
,如果你在我的javascript發現有什麼問題請指正
瞭解如何在PHP中啓用錯誤/警告報告,然後使用Fiddler或Firebug檢查PHP的響應。我非常懷疑它會給你一個警告,說明輸出寫入後不能更改標題 - 在設置響應標題之前,你正在迴應你的MySQL錯誤(本身可能是一個壞主意)。 – tomfumb
爲什麼你總是執行'sendResponse()'?你不想在那裏有一個'else',所以只有當'if'條件失敗時纔會調用它。 – pimvdb
你是對的我很抱歉粘貼它,我做了一個錯誤將現在糾正它 – indr