2017-08-27 61 views
0

我试图建立一个注册表格那里我需要检查的值加载功能的AJAX是错误。有没有办法检查ajax函数的返回值是真是假?

我卡在这个问题这里是我的代码

$("button").click(function(){ 
    $("#error").load("newEmptyPHP.php",{email:mail}); 
}) 

newEmptyPHP.php

<?php 
     $mail=$_POST["email"]; 
     $db=new PDO("mysql:host=localhost;dbname=the_scops","root",""); 
     $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     $STH=$db->prepare("SELECT email FROM signup WHERE email=?"); 
     $STH->execute([$mail]); 
     if($STH->rowCount() == 1){ 
      //echo "<script>$('#error').html('Email alreday exist')</script>"; 
      return false; 
     } 
     else{ 
      return true; 
     } 

**

+0

当您向'newEmptyPHP.php'发出请求时,您会收到响应。响应包含标题和正文。您可以使用它们来提供操作的“结果”。 (即:使用http状态码,使用200 OK和4xx)。 – Federkun

回答

1

您必须在json格式中回显true或false。 ......就这样。

<?php 

    $result = array(); 
    $mail=$_POST["email"]; 
    $db=new PDO("mysql:host=localhost;dbname=the_scops","root",""); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $STH=$db->prepare("SELECT email FROM signup WHERE email=?"); 
    $STH->execute([$mail]); 
    if($STH->rowCount() == 1){  
     $result['status'] = false; 
    } 
    else{ 
     $result['status'] = true; 
    } 

    echo json_encode($result); 
    exit(0); 

?> 

编辑: 你可以处理响应这样的。

$("button").click(function(){ 
    $("#error").load("newEmptyPHP.php",{email:mail},function(response){ 
     result = $.parseJSON(response); 
     if(result.status){ 
      //true 
     } else { 
      //false 
     } 
    }); 
}); 
2

你知道,Ajax调用返回的输出功能或脚本不是其评价。我强烈怀疑当你手动调用你的代码时你会得到一个空的响应,而且对于发出ajax请求的javascript也是如此。

如果你是显示所有参与程序的代码,并没有任何的中间件来装饰你的返回值,你应该修改你的脚本在类似这样的方式:

<?php 
    $mail=$_POST["email"]; 

    $db=new PDO("mysql:host=localhost;dbname=the_scops","root",""); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $STH=$db->prepare("SELECT email FROM signup WHERE email=?"); 
    $STH->execute([$mail]); 
    $result = []; 
    if($STH->rowCount() == 1){ 
     // echo "<script>$('#error').html('Email alreday exist')</script>"; 
     $result["success"] = false; 
     $result["message"] = 'Email already exists'; 
    } else{ 
     $result["success"] = true; 
    } 
    // comunicate to the client that the response is json encoded 
    header('Content-type:application/json'); 
    // output the response 
    echo json_encode($result); 

JavaScript部分有(我不习惯jquery,仔细考虑):

$("button").click(function(){ 
    $.get("newEmptyPHP.php",{email:mail}, function(data) { 
     if (data.success == false) { 
      $('#error').html(data.message); 
     } else { 
     // do wathever you need in case of data.success 
     } 
    }) 
}) 
相关问题