[英]php ajax post request
我正在尝试对名为“ sendMail.php”的文件进行ajax发布请求。 我不知道出什么问题了,我只是看不到。
js可以正常工作,它会在chrome开发工具中记录来自输入的值,我可以看到它已发送到PHP文件... chrome开发工具屏幕
我有点生疏,上一个PHP代码大约是在一年前。
在下面,您将找到我的PHP和js代码。
文件夹树(index.html是用于操作的主文件):
PHP:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
header('Content-Type: application/json');
$requestbody = file_get_contents('php://input','r');
$jsonbody = json_decode($requestbody, true);
$action = $jsonbody['action'];
switch($action){
case "sendMail":
$name = $requestbody->{'name'};
$gsm = $requestbody->{'gsm'};
$mail = $requestbody->{'mail'};
$msg = $requestbody->{'msg'};
$response = json_encode( '{"naam":"'.$name.'","gsm":"'.$gsm.'","mail":"'.$mail.'"}');
echo $response;
break;
}
}else{
http_response_code(405);
header('Content-Type: application/json');
$response = '{"error":"request method is not allowed."}';
echo($response);
}
?>
JS:
function sendMail(){
console.log(document.getElementById("mail_naam").value);
console.log(document.getElementById("mail_gsm").value);
console.log(document.getElementById("mail_mail").value);
console.log(document.getElementById("mail_msg").value);
$.ajax({
method:'POST',
url:'mail/sendMail.php',
dataType:'json',
data: {
"action":"sendMail",
"name": document.getElementById("mail_naam").value,
"gsm": document.getElementById("mail_gsm").value,
"mail":document.getElementById("mail_mail").value,
"msg": document.getElementById("mail_msg").value
}
}).done(function(data) {
console.log("succes")
console.log(data);
var result = JSON.parse(data);
console.log(result)
});
}
Ajax中没有method
参数,因此将其替换为type
。
试试下面的代码:
$.ajax({
type:'POST',
url:'mail/sendMail.php',
dataType:'json',
data: {
"action":"sendMail",
"name": document.getElementById("mail_naam").value,
"gsm": document.getElementById("mail_gsm").value,
"mail":document.getElementById("mail_mail").value,
"msg": document.getElementById("mail_msg").value
}
}).done(function(data) {
console.log("succes");
console.log(data);
var result = JSON.parse(data);
console.log(result);
});
我添加了这个,这可行:
PHP
if(empty($action) || $jsonbody){ $action = $_POST['action']; }
switch ($action) {
case "sendMail":
$name = $_POST["name"];
$gsm = $_POST['gsm'];
$mail = $_POST['mail'];
$msg = $_POST['msg'];
mailVraag($mail,$name,$msg);
mailVraag("achiel@protoware.be","protoware",$msg . "tel:".$gsm ."email: ".$mail);
$response = json_encode( '{"naam":"'.$name.'","gsm":"'.$gsm.'","mail":"'.$mail.'"}');
echo $response;
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.