表格部分:
<script type="text/javascript" src="js/aboneol.js"></script>
<h4>haberdar olun</h4>
<div class="news_letter">
<span id="aboneolhata"></span>
<form action="" method="post" onsubmit="return false;" id="abone">
<input type="text" name="email" placeholder="E-posta adresiniz" />
<input type="submit" onclick="$.aboneol();" value="abone ol" />
</form>
</div>
Jquery部分:
$.aboneol = function(){
var deger = $("form#abone").serialize();
$.ajax({
url: "aboneol.php",
data: deger,
dataType: "json",
type: "post",
success: function(response){
if(response.error == 0){
$(".news_letter").html(response.message);
}else{
$("#aboneolhata").html(response.message);
}
}
});
}
这是php部分:
<?php
$email = $_POST["email"];
$email = trim($email);
if(empty($email)){
$response["error"] = 1;
$response["message"] = "Boş Bırakamazsınız..";
}else if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$response["error"] = 1;
$response["message"] = "Hatalı E-posta..";
}else{
require "database.php";
$pdo = Database::connect();
$sql = "INSERT INTO aboneler (email) VALUES (:email)";
$q = $pdo->prepare($sql);
$q->execute(array(
':email'=>$email,
));
$response["error"] = 0;
$response["message"] = $email;
}
echo json_encode($response);
?>
Ajax将电子邮件发送到php,http响应代码为200.但成功方法不起作用。我也无法在成功方法中看到任何json响应。如何解决这个问题呢?
答案 0 :(得分:3)
您应该将响应内容类型设置为application/json
。如果你没有设置它,你可以在收到响应时,从中创建json对象(或字典)。
所以:
1 - 设置php响应头:
header("Content-type: application/json");
2 - 或者如果你没有在php中设置标题,请在javascript中解析响应:
success: function(response){
response = JSON.parse(response);
if(!response['error']){
...