我有一个将值发送到变量$ _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