php - 使脚本响应来自 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");
};
});
});
});
解决方案
尝试这个:
<?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);
}
});
推荐阅读
- javascript - 在 React-Native 中更改屏幕时如何保存数据?
- font-awesome - 如何添加字体真棒图标?
- sql - 如何引用具有多个主键的 postgres 表
- python - 使用 PyMongo update_one() 时重复
- android - 无法在没有向后兼容性的情况下创建新活动或新项目
- java - 如何使用将哈希图转换为 JsonObject 的 gson
- android - 无法使用 NavigationComponents 更改标签标题
- javascript - 使用构造函数 (JavaScript) 创建选项
- lightbox2 - 控件未显示在灯箱中
- database - MS Access 未在工作区中追加表