我正在使用的代码工作正常,但我有点卡住尝试从成功函数加载新页面。最简单的方法是,如何过滤来自php后端的数据来做出决策?例如,我在后端testajax.php页面和ajax成功函数测试中为某些条件设置了一个条件。在php中,它将使用if语句。我对jquery很新,所以我会很感激如何实现这一点。感谢
$.ajax({
type: "POST",
url: "testajax.php",
data: data,
success: function (data) {
$('#login_message').html(data);
//$(ok).val('Logged In');
//$("#login").get(0).reset();
//$("#form").dialog('close');
$.mobile.changePage( "admin/index.php/", { transition: "slideup"} );
},
error:function (xhr, ajaxOptions, thrownError){
alert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
testajax.php
<?php
// test wether the user session is already set
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
if($_SESSION['user']=='admin') {
echo 'Welcome Admin';
// for example, test data in ajax for
// this flag and if equal 1 then load admin/index.php
$flag = 'admin';
// end of flag
echo $flag;
}
else
echo 'Unknown User';
}
?>
答案 0 :(得分:1)
没有什么可以阻止你在jquery代码中使用if语句,所以你可以使用ajax回调:
if (data == 'Unknown User') {
alert('Unknown User');
} else {
//Do some other stuff here
}
答案 1 :(得分:1)
<?php
// test wether the user session is already set
session_start();
$userpost = mysql_real_escape_string($_POST['user']);
if (!isset($_SESSION['user'])) {
$_SESSION['user'] = $userpost;
if($_SESSION['user']=='admin') {
$flag = 'admin';
echo $flag;
}
else
echo 'Unknown User';
}
?>
ajax part
$.ajax({
type: "POST",
url: "testajax.php",
data: data,
success: function (data) {
$('#login_message').html(data);
if(data==='admin')
{
//redirect
$.mobile.changePage( "admin/index.php/", { transition: "slideup"} );
}
},
error:function (xhr, ajaxOptions, thrownError){
alert('There was an exception thrown somewhere');
alert(xhr.status);
alert(thrownError);
}
});
答案 2 :(得分:1)
如果请求是ajax请求,您可以检查该请求,并仅输出ajax部分所需的内容。
if(strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
//request by ajax
}
else
{
//regular request.
}