首页 > 解决方案 > 使脚本响应来自 PHP 的回声

问题描述

我希望我的 AJAX 脚本响应echo来自 PHP 的响应,但它不起作用。这是register.php:

<?php
  if (isset($_POST['username']))
  {
    require_once('dbconfig.php');
    $user = $_POST['username'];
    $pass = $_POST['password'];

    if (strlen($user) > 1) 
    {
      echo '{"status":success}';
    } 
    else if (strlen($user) < 1) 
    {
      echo '{"status":failed}';    
    }
  } else
    echo "Sesiunea nu mai este activa.";
?>
$(document).ready(function() {
  $('#btnRegister').click(function() {
    var user = $('#username').val();
    var pass = $('#password').val();
    var posting = $.post("http://localhost/univoo/ucp/universitati/dbfunc/register.php", {
      username: user, 
      password: pass
    });

    posting.done(function(data) {
      if (data.status == "success") {
        alert("Succes");
      } else if (data.status == "failed") {
        alert("failed");
      };
    });
  });
});

标签: phpjqueryajax

解决方案


尝试这个:

<?php
    if (isset($_POST['username'])) {

        require_once('dbconfig.php');
        $user = $_POST['username'];
        $pass = $_POST['password'];

        if (strlen($user) > 1) {
            $result = true;
        } else if (strlen($user) < 1) {
            $result = false;
        } else {
            $result = 'Sesiunea nu mai este activa.';
        }
        echo json_encode(compact('result'));
    }
?>

还有你的 JavaScript:

posting.done(function(data) {

    var response = JSON.parse(data);

    if (response.result === true) {
        alert('success');
    } else if (response.result === false) {
        alert('failed');
    } else {
        alert(response.result);
    }
});

推荐阅读