Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Ajax没有获得JSON值_Php_Json_Ajax - Fatal编程技术网

Php Ajax没有获得JSON值

Php Ajax没有获得JSON值,php,json,ajax,Php,Json,Ajax,我正在进行一个简单的登录测试,当字段为空时,代码会返回json响应,但当登录失败或成功时,代码不会返回json响应,如: 空字段-确定 登录成功-否 登录失败-否 请求: var loader = $('#trabalhando'); $(function() { $('form').submit(function(e) { loader.fadeIn("slow"); e.preventDefault(); $.ajax({

我正在进行一个简单的登录测试,当字段为空时,代码会返回json响应,但当登录失败或成功时,代码不会返回json响应,如:

  • 空字段-确定
  • 登录成功-否
  • 登录失败-否
请求:

var loader = $('#trabalhando');
$(function() {
    $('form').submit(function(e) {


        loader.fadeIn("slow");
        e.preventDefault();


        $.ajax({
            url: 'login.php',
            data: $(this).serialize(),
            method: 'post',
            dataType: 'JSON',
            success: function(data){
                loader.fadeOut("slow");
                console.log(data);
                alert(data.resp);
            },
            error: function(data) {
                alert(':(');
                loader.fadeOut("slow");
                console.log(data);
            }
        });

    });
});
答复:

<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "") { 

    $cpf = $_POST['cpf'];
    $passw = sha1(strrev(md5($_POST['pass'])));

    include 'config.php';

        $sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
        $chec = $db->prepare($sql);
        $chec->bindParam('cp', $cpf, PDO::PARAM_STR);
        $chec->bindParam('pw', $passw, PDO::PARAM_STR);
        $chec->execute();

        if ($chec->rowCount() > 0) {

            echo json_encode(array('resp' => 'nice'));

        } else {
            echo json_encode(array('resp' => 'nope'));
        }   

} else {
    echo json_encode(array('resp' => 'fields'));
}

?>


编辑:更新代码

您没有正确绑定参数,因此可能存在未处理的PDO错误。更改:

$chec->bindParam('cp', $cpf, PDO::PARAM_STR);
$chec->bindParam('pw', $passw, PDO::PARAM_STR);
致:

一般来说,数据库、文件和远程服务器操作(FTP、HTTP、SSH…)都非常严格,所以当您依赖这些操作时,请始终进行错误检查!您应该将查询分解成一个专门的函数,该函数执行正确的错误检查

/**
 * @param PDO $db       The PDO object with which to perform queries
 * @param string $sql   raw SQL (eg: "select * from t where a = :param" )
 * @param array $params Array of parameter names and values eg: [':param' => 'value']
 * @param string $error Will be filled with the error details if the DB operations fail
 * @return false|PDOStatement FALSE on error, or the statement on success
 */
function query(PDO $db, $sql, array $params, &$error){
    try{ 
        // error check every step!
        if(!$stmt = $db->prepare($sql)) throw new Exception($db->errorInfo()[2]);           
        if(!$stmt->execute($params)) throw new Exception($stmt->errorInfo()[2]);

        return $stmt; // return the $stmt for further processing
    }catch (Exception $e){
        $error = $e->getMessage();
        return false;
    }
}
现在,您可以更简单地执行查询:

$stmt = query($db, $sql, $params, $error);

// decide what to do on failure
if(!$stmt) die($error);

// now it's safe to use $stmt to fetch results, count rows...
更新 你说:


失败与成功完全相同,装载机已被装载并处于警戒状态,但这一次是带着一张悲伤的脸处于警戒状态

这是意料之中的success仅仅意味着服务器响应正常。它没有说明json字符串中的内容。如果要触发
错误
Ajax回调,服务器需要设置如下错误:

http_response_code(401);
echo json_encode(array('resp' => 'nope'));
更新2 要了解Ajax调用触发的错误的详细信息,请修改回调并检查结果:

error: function(jqXHR, textStatus, errorThrown){
          console.log('textStatus: ' + textStatus);
          console.log('errorThrown: ' + errorThrown);
        }
可能您的服务器正在发送其他内容以及破坏输出的JSON。请尝试关闭脚本顶部的缓冲区,并立即使用echo退出:

<?php
ob_end_clean(); // at top of script

//try echoing this way
die(json_encode(array('resp' => 'nice')));
die(json_encode(array('resp' => 'nope')));

您的config.php文件或sql语句似乎有问题

尝试将代码放入try catch,然后以json的形式返回错误:

<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "")
{ 

   $cpf = $_POST['cpf'];
   $passw = sha1(strrev(md5($_POST['pass'])));
   try
   {
       include 'config.php';

      $sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
      $chec = $db->prepare($sql);
      $chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
      $chec->bindParam(':pw', $passw, PDO::PARAM_STR);
      $chec->execute();
      if ($chec->rowCount() > 0)
      {
          echo json_encode(array('resp' => 'nice'));
      }
      else
      {
          echo json_encode(array('resp' => 'nope'));
      }
   }
   catch(Exception $e)
   {
        echo json_encode($e->getMessage());
   }   

} 
else
{
    echo json_encode(array('resp' => 'fields'));
}

?>


编辑:合并@belletJuice的修复程序

检入浏览器开发工具、网络面板、响应请求的内容以及状态代码。我删除了ajax调用,并在表单上添加了操作,在login.php页面中,一切正常,它显示了nope和良好的响应,ajax只是没有返回它们,有什么想法吗?@tlckpl如果你在success()处理程序中执行
console.log(data)
,你会在浏览器开发工具中看到什么?它调用我几分钟前添加的错误方法:Object{readyState:4,responseText:“{”resp:“nope”}”,status:200,statusText:“OK”}@tlckpl我不知道怎么了。如果您正在处理的代码与本页上的代码不同,我真的无法帮助您失败与成功完全相同,加载并发出警报,但这次是带着悲伤的表情发出警报
<?php
header('Content-Type: application/json');
if (isset($_POST['cpf']) && isset($_POST['pass']) && $_POST['cpf'] != "" && $_POST['pass'] != "")
{ 

   $cpf = $_POST['cpf'];
   $passw = sha1(strrev(md5($_POST['pass'])));
   try
   {
       include 'config.php';

      $sql = "SELECT * FROM users WHERE cpf = :cp AND passwd = :pw";
      $chec = $db->prepare($sql);
      $chec->bindParam(':cp', $cpf, PDO::PARAM_STR);
      $chec->bindParam(':pw', $passw, PDO::PARAM_STR);
      $chec->execute();
      if ($chec->rowCount() > 0)
      {
          echo json_encode(array('resp' => 'nice'));
      }
      else
      {
          echo json_encode(array('resp' => 'nope'));
      }
   }
   catch(Exception $e)
   {
        echo json_encode($e->getMessage());
   }   

} 
else
{
    echo json_encode(array('resp' => 'fields'));
}

?>