【发布时间】:2019-01-31 19:34:01
【问题描述】:
我知道这个问题已经被问过很多次了,但是我已经尝试了所有的解决方案,但对我没有任何效果,所以我的问题是我无法使用 ajax 从服务器加载json 响应我有我的script.js在 js 文件夹中,我的 sendMail.php 在包含文件夹中,index.php 在根文件夹中,当我提交一些信息时,状态为 200 表示一切正常,但我也无法用我的 php 代码检查它们,因为 json回复
index.php
<!DOCTYPE html>
<html>
<head>
<title>Booking</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/script.js"></script>
</head>
<body>
<form action="includes/sendMail.php" method="POST" name="reservation-form" id="reservation-form">
<div>
<select class="select-dropbox" name="mail-hour">
<option value="" disabled selected>Hour</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div>
<input type="text" name="mail-phone" placeholder="Phone Number"
>
</div>
<div>
<input type="text" name="mail-email" placeholder="Email Address" >
</div>
<div>
<textarea name="mail-msg" placeholder="Your Message" ></textarea>
</div>
<div id="check-form">
</div>
<div>
<button id="mail-submit" name="mail-submit" type="submit">BOOK A TABLE</button>
</div>
</form>
</body>
</html>
script.js
$(document).ready(function(){
$('#mail-submit').click(function(event){
event.preventDefault();
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
url: 'includes/sendMail.php',
type: 'POST',
data: $('#reservation-form').serialize(),
beforeSend: function(xhr){
$('#mail-submit').html('SENDING...');
},
success: function(response){
if(respo,se){
alert(response);
if(response['signal'] == 'ok'){
$('#check-form').html('<div>'+ response['res-msg'] +'</div>');
}
else{
$('#check-form').html('<div>'+ response['res-msg'] +'</div>');
}
}
},
error: function(xhr, status, thrown){
alert("xhr: "+xhr+" status: "+status+" thrown: "+thrown);
$('#check-form').html('<div>An Error occurs. Please try again.</div>');
},
complete: function(){
$('#mail-submit').html('BOOK A TABLE');
}
});
});
});
sendMail.php
<?php
if (isset($_POST['mail-submit'])) {
$hour = trim($_POST['mail-hour']);
$phone = trim($_POST['mail-phone']);
$email = trim($_POST['mail-email']);
$message = trim($_POST['mail-msg']);
if($hour != null && $phone != null && $email != null){
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$signal = 'bad';
$msg = 'Invalid email. Please check';
}
else {
$signal = 'ok';
$msg = 'Form submitted';
}
}
else{
$signal = 'bad';
$msg = 'Please fill in all the fields.';
}
$data = array(
'signal' => $signal,
'res-msg' => $msg
);
echo json_encode($data);
}
?>
【问题讨论】:
-
你能帮我吗?我今天真的需要修复这个代码,它对我不起作用
-
您尝试发送的 JSON 负载是什么?
-
我正在尝试发送
$data['signal']和$data['res-msg'] -
当您有
dataType: 'JSON'时,您不需要var response=parseJSON(res);... .ajax 方法已经返回res作为要在success回调中使用的对象。同样由于告诉 ajax 会发生什么,你在 php 端真的不需要header("Content-Type: application/json", true);。 -
@IncredibleHat 我已经删除了你说的所有代码,但仍然无法正常工作
标签: javascript php jquery json ajax