什么';处理从PHP JavaScript(AJAX)返回的数据最合适/最友好的方法是什么?
编辑:好吧,现在我想起来了,JSON听起来确实不错,只要我的代码正确,就不应该有语法错误来破坏它或任何东西什么';处理从PHP JavaScript(AJAX)返回的数据最合适/最友好的方法是什么?,javascript,php,ajax,response,responsetext,Javascript,Php,Ajax,Response,Responsetext,编辑:好吧,现在我想起来了,JSON听起来确实不错,只要我的代码正确,就不应该有语法错误来破坏它或任何东西 晚上好 一直困扰我的是如何在AJAX请求中处理从PHP返回的数据,甚至如何返回数据 假设我有一个登录表单,它通过AJAX处理提交的表单数据。为了简单起见,我们使用GET “page.php?username=Foo&password=bar” 以下是困扰我的问题,以及为什么我会感到强迫,觉得我需要知道正确的方法来做到这一点: 我发送了数据,数据已经处理完毕现在怎么办? 说明我的用户名和密
晚上好 一直困扰我的是如何在AJAX请求中处理从PHP返回的数据,甚至如何返回数据 假设我有一个登录表单,它通过AJAX处理提交的表单数据。为了简单起见,我们使用GET “page.php?username=Foo&password=bar” 以下是困扰我的问题,以及为什么我会感到强迫,觉得我需要知道正确的方法来做到这一点: 我发送了数据,数据已经处理完毕现在怎么办? 说明我的用户名和密码有效/正确。我该怎么办 在PHP中返回true?一根绳子 那么我该如何处理JavaScript呢
if(ajaxRequest.responseText=="true"){
//Username and password are correct! Execute this...
}
我认为一个很酷的想法是将JSON对象作为字符串返回,并通过JavaScript进行解析
var object=JSON.parse(ajaxRequest.responseText);
if(object.success=="true"){
//Username and password are correct! Execute this...
}
但是,如果我的用户名和密码组合是…错误的怎么办?
我是通过PHP返回false,还是再次返回字符串
在真和假之间,只有两种选择:
1.用户名和密码是正确的
2.用户名和密码不正确
但是如果用户名根本不存在呢?返回“false”并不能帮助我确切地告诉客户为什么他们不能登录
深入研究我的强迫症,如何处理意外或解析错误
如果存在某种DB连接错误或解析错误,如何返回该错误以告知用户?我试图尝试…并捕捉语法错误,但我没有运气
我最近的一个想法是:
如果所有操作都正确执行,并且用户名和密码存在(回到最初的场景),那么我们不会返回任何内容。responseText将是一个空字符串。这意味着用户已成功登录
否则,如果出现错误,执行返回某些内容(通常是字符串)并将其显示为错误
我这样做对吗?我走对了吗?一种相当常见的模式是返回一个错误数组,在您的例子中,它可能是一个JSON对象。如果错误数组为空,则可以继续,如果不是,则将错误显示给用户。一种相当常见的模式是返回错误数组,在您的情况下,该数组可能是JSON对象。如果错误数组为空,则可以继续,如果不是,则将错误显示给用户。一种相当常见的模式是返回错误数组,在您的情况下,该数组可能是JSON对象。如果错误数组为空,则可以继续,如果不是,则将错误显示给用户。一种相当常见的模式是返回错误数组,在您的情况下,该数组可能是JSON对象。如果错误数组为空,则可以继续,如果不是,则将错误显示给用户。我认为您对If和but的响应过于复杂 下面是我曾经用过的一个老例子。我使用以下ajax通过ajax将用户名/密码发送到php文件
$.ajax({
type: "POST",
url: SITE_URL+"ajax_files/ajax_login.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.success=='y') {
window.location.href='index.php';
} else {
$('#messagesnormal').hide();
//Show results div
$('#resultsAjax').show();
//Put received response into result div
//$('#resultsAjax').html(data.msg);
}
}
});
下面是我的php文件代码
header('Content-Type: application/json');
include("../config/config.php");
$username = trimdata($_POST['username']);
$password = trimdata($_POST['password']);
$r = $db->select("SELECT * FROM users where email = '".dbAddslashes($username)."' and password='".dbAddslashes($password)."' and status = '1' and locked_by_admin = '0'");
if($db->row_count > 0) {
while ($row=$db->get_row($r, 'MYSQL_ASSOC')) {
$_SESSION["userdata"]["userid"] = $row['user_id'];
$_SESSION["userdata"]["usertype"] = $row['type'];
$_SESSION["userdata"]["useremail"] = $row['email'];
$_SESSION["userdata"]["name"] = $row['name'];
if($_SESSION["userdata"]["usertype"]=='1') {
$_SESSION["userdata"]["userrole"] = 'admin';
} else {
$_SESSION["userdata"]["userrole"] = 'user';
}
$_SESSION["userdata"]["last_login"] = $row['last_login'];
$_SESSION["userdata"]["last_login_ip"] = $row['last_login_ip'];
$success = 'y';
$msg = 'login successfull';
/*Insert login time and IP*/
$data = array('last_login' => time(), 'last_login_ip' => getRealIPAddr());
$rows = $db->update_array('users', $data, "user_id=".$row['user_id']);
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
} else {
$success = 'n';
$msg = '<div class="gagalsmall">Invalid credentials.Please try again.</div>';
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
exit;
其中成功是从php文件分配的
希望这能对你有所帮助。我认为你的回答过于复杂化了 下面是我曾经用过的一个老例子。我使用以下ajax通过ajax将用户名/密码发送到php文件
$.ajax({
type: "POST",
url: SITE_URL+"ajax_files/ajax_login.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.success=='y') {
window.location.href='index.php';
} else {
$('#messagesnormal').hide();
//Show results div
$('#resultsAjax').show();
//Put received response into result div
//$('#resultsAjax').html(data.msg);
}
}
});
下面是我的php文件代码
header('Content-Type: application/json');
include("../config/config.php");
$username = trimdata($_POST['username']);
$password = trimdata($_POST['password']);
$r = $db->select("SELECT * FROM users where email = '".dbAddslashes($username)."' and password='".dbAddslashes($password)."' and status = '1' and locked_by_admin = '0'");
if($db->row_count > 0) {
while ($row=$db->get_row($r, 'MYSQL_ASSOC')) {
$_SESSION["userdata"]["userid"] = $row['user_id'];
$_SESSION["userdata"]["usertype"] = $row['type'];
$_SESSION["userdata"]["useremail"] = $row['email'];
$_SESSION["userdata"]["name"] = $row['name'];
if($_SESSION["userdata"]["usertype"]=='1') {
$_SESSION["userdata"]["userrole"] = 'admin';
} else {
$_SESSION["userdata"]["userrole"] = 'user';
}
$_SESSION["userdata"]["last_login"] = $row['last_login'];
$_SESSION["userdata"]["last_login_ip"] = $row['last_login_ip'];
$success = 'y';
$msg = 'login successfull';
/*Insert login time and IP*/
$data = array('last_login' => time(), 'last_login_ip' => getRealIPAddr());
$rows = $db->update_array('users', $data, "user_id=".$row['user_id']);
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
} else {
$success = 'n';
$msg = '<div class="gagalsmall">Invalid credentials.Please try again.</div>';
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
exit;
其中成功是从php文件分配的
希望这能对你有所帮助。我认为你的回答过于复杂化了 下面是我曾经用过的一个老例子。我使用以下ajax通过ajax将用户名/密码发送到php文件
$.ajax({
type: "POST",
url: SITE_URL+"ajax_files/ajax_login.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.success=='y') {
window.location.href='index.php';
} else {
$('#messagesnormal').hide();
//Show results div
$('#resultsAjax').show();
//Put received response into result div
//$('#resultsAjax').html(data.msg);
}
}
});
下面是我的php文件代码
header('Content-Type: application/json');
include("../config/config.php");
$username = trimdata($_POST['username']);
$password = trimdata($_POST['password']);
$r = $db->select("SELECT * FROM users where email = '".dbAddslashes($username)."' and password='".dbAddslashes($password)."' and status = '1' and locked_by_admin = '0'");
if($db->row_count > 0) {
while ($row=$db->get_row($r, 'MYSQL_ASSOC')) {
$_SESSION["userdata"]["userid"] = $row['user_id'];
$_SESSION["userdata"]["usertype"] = $row['type'];
$_SESSION["userdata"]["useremail"] = $row['email'];
$_SESSION["userdata"]["name"] = $row['name'];
if($_SESSION["userdata"]["usertype"]=='1') {
$_SESSION["userdata"]["userrole"] = 'admin';
} else {
$_SESSION["userdata"]["userrole"] = 'user';
}
$_SESSION["userdata"]["last_login"] = $row['last_login'];
$_SESSION["userdata"]["last_login_ip"] = $row['last_login_ip'];
$success = 'y';
$msg = 'login successfull';
/*Insert login time and IP*/
$data = array('last_login' => time(), 'last_login_ip' => getRealIPAddr());
$rows = $db->update_array('users', $data, "user_id=".$row['user_id']);
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
} else {
$success = 'n';
$msg = '<div class="gagalsmall">Invalid credentials.Please try again.</div>';
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
exit;
其中成功是从php文件分配的
希望这能对你有所帮助。我认为你的回答过于复杂化了 下面是我曾经用过的一个老例子。我使用以下ajax通过ajax将用户名/密码发送到php文件
$.ajax({
type: "POST",
url: SITE_URL+"ajax_files/ajax_login.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.success=='y') {
window.location.href='index.php';
} else {
$('#messagesnormal').hide();
//Show results div
$('#resultsAjax').show();
//Put received response into result div
//$('#resultsAjax').html(data.msg);
}
}
});
下面是我的php文件代码
header('Content-Type: application/json');
include("../config/config.php");
$username = trimdata($_POST['username']);
$password = trimdata($_POST['password']);
$r = $db->select("SELECT * FROM users where email = '".dbAddslashes($username)."' and password='".dbAddslashes($password)."' and status = '1' and locked_by_admin = '0'");
if($db->row_count > 0) {
while ($row=$db->get_row($r, 'MYSQL_ASSOC')) {
$_SESSION["userdata"]["userid"] = $row['user_id'];
$_SESSION["userdata"]["usertype"] = $row['type'];
$_SESSION["userdata"]["useremail"] = $row['email'];
$_SESSION["userdata"]["name"] = $row['name'];
if($_SESSION["userdata"]["usertype"]=='1') {
$_SESSION["userdata"]["userrole"] = 'admin';
} else {
$_SESSION["userdata"]["userrole"] = 'user';
}
$_SESSION["userdata"]["last_login"] = $row['last_login'];
$_SESSION["userdata"]["last_login_ip"] = $row['last_login_ip'];
$success = 'y';
$msg = 'login successfull';
/*Insert login time and IP*/
$data = array('last_login' => time(), 'last_login_ip' => getRealIPAddr());
$rows = $db->update_array('users', $data, "user_id=".$row['user_id']);
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
} else {
$success = 'n';
$msg = '<div class="gagalsmall">Invalid credentials.Please try again.</div>';
print json_encode(array('success' => $success, 'msg' => $msg));
exit;
}
exit;
其中成功是从php文件分配的
希望这能对您有所帮助。我个人的偏好是使用JSON,这绝对不是正确的做法 因此,我有一个JavaScript函数,在提交表单时,它将表单数据转换为JSON字符串,并将其发布到服务器 然后服务器处理它,并返回另一个JSON对象。因此,在您的登录示例中,服务器将收到:
{"username":"Foo","password":"bar"}
它将返回其中一个:
{"ok":false,"error":"No user with that name was found."}
{"ok":false,"error":"The password you entered was incorrect."}
{"ok":false,"error":"Failed to log you in (error code: ###)"}
{"ok":true,"redirect":"/home"}
每个AJAX请求响应都有这个“ok”属性。如果为false,则会有一个“error”属性说明发生了什么(根据具体情况,可能还会有其他数据)。成功时,“ok”属性为真。很多请求都是自己获取{“ok”:true}
的,但有时这里也有额外的数据
正如我所说,这不是一种“正确”的方法,但我喜欢它,而且它是一贯的
编辑:忘了提到PHP错误
接收服务器响应的JavaScript尝试使用
try…catch
块将其解析为JSON。如果解析失败,则表明存在服务器错误。在这种情况下,会弹出一条错误消息,其中包含来自服务器的原始响应,并带有一条提示,建议用户就错误消息与我联系。我个人的偏好是使用JSON,这绝不是正确的做法
因此,我有一个JavaScript函数,在提交表单时,它将表单数据转换为JSON字符串,并将其发布到服务器
然后,服务器继续运行