php后端对ajax请求的响应应该如何?
Posted
技术标签:
【中文标题】php后端对ajax请求的响应应该如何?【英文标题】:How should be the response to an ajax request in php backend? 【发布时间】:2020-12-20 11:19:21 【问题描述】:我试图在客户端取得成功,但我做不到。如果我把
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;
?>
【问题讨论】:
【参考方案1】:我会尝试以这种方式执行 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>
【讨论】:
我使用了 statusCode: 200: function()..... 并且成功了。非常感谢。以上是关于php后端对ajax请求的响应应该如何?的主要内容,如果未能解决你的问题,请参考以下文章