php - php后端对ajax请求的响应应该如何?
问题描述
我试图在客户端取得成功,但我做不到。如果我把
error:function(data){
console.log(data);
console.log('error');
}
ajax 请求中的这段代码捕获了一些东西,但它不应该出错。
我尝试了很多东西,但找不到解决方案。
这是我在客户端的ajax请求;
<script>
$(document).on("submit", "#request-form", function(event){ //request-form id li form post edildiğinde
event.preventDefault();
var serialized = $(this).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){ //formda boş yer var ise
alert("Fill in all fields");
}else{
$.ajax({
url: "http://127.0.0.1/rent_website/mail-sender/mail.php", //"https://stanstedcab.co.uk/project/mail-sender/mail.php",
type: "POST",
data: serialized,
dataType: "json",
function(data, status) {
console.log('function works');
if (data.success) {
console.log(data);
console.log('Başarılı');
} else {
console.log('else', data)
}
},
});
}
});
</script>
这里是后端;
<?php
$response = array();
if ($_POST){
if(isset($_POST["your-pickup"]) && isset($_POST["your-drop"]) && isset($_POST["Vehicle"]) &&
isset($_POST["meeting-time"]) && isset($_POST["your-name"]) && isset($_POST["your-phone"]) &&
isset($_POST["your-email"]) && isset($_POST["your-message"])) {
//here some mail settings
if($mail->Send()){
$message = "Email sent";
$response["success"] = true;
$response["message"] = $message;
echo json_encode($response);
return $response;
} else {
$response = array('result' => 'Email couldn\'t sent', 'success' => false);
echo json_encode($response);
return $response;
}
}else{
$response = array('result' => 'Fill all fields.', 'success' => false);
echo json_encode($response);
return $response;
}
}
?>
解决方案
我会尝试以这种方式执行 Javascript,如示例中所示:https ://api.jquery.com/jquery.ajax/
<script>
$(document).on("submit", "#request-form", function(event){ //request-form id li form post edildiğinde
event.preventDefault();
var serialized = $(this).serialize();
if(serialized.indexOf('=&') > -1 || serialized.substr(serialized.length - 1) == '='){ //formda boş yer var ise
alert("Fill in all fields");
}else{
$.ajax({
url: "http://127.0.0.1/rent_website/mail-sender/mail.php", //"https://stanstedcab.co.uk/project/mail-sender/mail.php",
type: "POST",
data: serialized,
dataType: "json"
}).done(function(data) {
console.log('function works');
if (data.success) {
console.log(data);
console.log('Başarılı');
} else {
console.log('else', data)
}
});
}
});
</script>
推荐阅读
- javascript - 基于表单字段数据的上传目录厉害吗?
- .net - .NET 框架 4.8 的传输层安全性 (TLS 1.3)
- scala - 为什么 cp 命令在不注意添加 -e 选项的情况下会出错?
- shopify - 太多/无限循环问题 - Shopify
- json - 如何使用 Swift 5 从 URL 解析 JSON 数据并附加到 UiLabel
- java - 带有 Libvirt c 代码的 JNA。我做错了什么?
- azure - Azure 中的故障域和更新域
- html - 如何将图像放置在不同图像旁边的文本下?
- python - 为什么 torch.FloatTensor([[[0,1,2],[3,4,5]],[[6,7,8],[9,10,11]]]) 的大小是 [2,2, 3]?
- amazon-web-services - 将 S3 文件存档到 Glacier