duanfei8149 2015-04-19 16:44
浏览 55
已采纳

JQuery Ajax Json响应不起作用

Form part :

<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 part :

$.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);
            }
        }
    });
}

And here is php part :

<?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 sends the email to php, and http response code is 200. But success method does not work. Also i cant see any json response in success method. How to solve this problem?

  • 写回答

1条回答 默认 最新

  • dph19153 2015-04-19 21:05
    关注

    You should set the response content-type to application/json. if you didn't set it, you can when receive the response, make json object (or dictionary) from it.

    So:

    1 - set php response header:

    header("Content-type: application/json");
    

    2 - or if you don't set header in php, parse response in javascript:

    success: function(response){
            response = JSON.parse(response);
            if(!response['error']){
            ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化