[英]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.