如果php返回true,则重定向页面jQuery ajax

时间:2022-12-05 14:23:01

i quite new to ajax and i am bit confused...

我对ajax很新,我有点困惑......

I have php function that returns a boolean(as 1,0) each time is called.

我有php函数,每次调用时返回一个布尔值(为1,0)。

What i need is to somehow request that value and process it, if it's 0 to do nothing and if it's 1 to show an alert message and redirect to index and destroy session.

我需要的是以某种方式请求该值并处理它,如果它是0什么也不做,如果它是1来显示警报消息并重定向到索引和销毁会话。

Should i encode the value into json in the php file or not?

我应该将值编码到php文件中的json中吗?

js:

$.post("activity.php", function(data,success) {
    if (data == '0') {
        alert("You are logged out");
        window.location = 'index.php';
    }
});

PHP:

$activity = $userdao->activity($_SESSION['sessionid']);
if ($activity == 0) {
    $logout->userLogout($userid);
    session_destroy();
}

1 个解决方案

#1


0  

If you are going to process the response from the server using json. Then you need to encode the result on sever side. and you also need to change the response header content_type to application/json

如果您要使用json处理来自服务器的响应。然后你需要在服务器端编码结果。您还需要将响应标头content_type更改为application / json

<?php
    header('Content-type: application/json');
    $data = array();
    $data['result'] = true;
    echo json_encode($data);

and on your client side

并在您的客户端

$.post("activity.php", function(data,success) {
    console.log(data);
}
});

and check your result from debug console in your browser.

并在浏览器中从调试控制台检查结果。

#1


0  

If you are going to process the response from the server using json. Then you need to encode the result on sever side. and you also need to change the response header content_type to application/json

如果您要使用json处理来自服务器的响应。然后你需要在服务器端编码结果。您还需要将响应标头content_type更改为application / json

<?php
    header('Content-type: application/json');
    $data = array();
    $data['result'] = true;
    echo json_encode($data);

and on your client side

并在您的客户端

$.post("activity.php", function(data,success) {
    console.log(data);
}
});

and check your result from debug console in your browser.

并在浏览器中从调试控制台检查结果。