phonegap:将数据库值存储在本地存储中

时间:2016-10-15 14:51:35

标签: php jquery ajax cordova phonegap-plugins

这是我第一次使用phonegap和本地存储。所以,如果我问傻事,那么我道歉。

我正在尝试为移动应用创建登录/注册页面。我在html / js / jquery中创建了一个前端页面,后端在php中。

在php中我们使用session来存储一些数据但是在html中没有会话。但是我知道我们可以使用本地存储来存储这些值。 这是我的PHP代码,用于身份验证。

<?php
session_start();
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
require_once('include/db.php');
require_once('functions.php');
$res=array();
$res['errors']=array();
if(isset($_POST)) {
    if(empty($_POST['email'])) {
        array_push($res['errors'], "Email could not be empty");
    }
    if(empty($_POST['password'])) {
        array_push($res['errors'], "Password could not be empty");
    }
    if(!empty($_POST['email']) && !isValidEmail($_POST['email'])) {
        array_push($res['errors'], "Invalid Email Format");
    }

        $email = $_POST['email'];
        $password = $_POST['password'];
        $now = date('Y-m-d H:i:s'); 

    if(empty($res['errors'])) { 
        $result = $mysqli->prepare("SELECT uid,pic,fname,last_seen FROM users where email= ? and password = ? and status = '1'");
        $result ->bind_param("ss", $email, $password);
        $result->execute();
        $result->store_result();

        $result->bind_result($uid, $pic, $fname, $last_seen);
        if($result->num_rows == 1){

             while ($result->fetch()) {
                        $_SESSION['uid'] = $uid;
                        $_SESSION['pic'] = $pic;
                        $_SESSION['name'] = $fname;
                        $_SESSION['last_login'] = $last_seen;
            }

            $res['success'] = true;
        }
        else{
            array_push($res['errors'], 'Invalid login details');
            $res['success'] = false;

        }
    }else{
        $res['success'] = false;        
    }
    session_write_close();
     echo json_encode($res);
}
?>

这是ajax代码。

<script type="text/javascript">
$('document').ready(function()
{
            $("#login").on("submit", function(e) {              
                e.preventDefault;
                var btn = $('#btn-login');
                btn.button('loading');
                $.ajax({
                    type: 'post',
                    url: 'loginexec.php',
                    cache: false,
                    dataType: 'json',
                    data: $('form#login').serialize(),
                    beforeSend: function() { 
                        $("#validation-errors").hide().empty(); 
                    },
                    success: function(data) {
                        if(data.success == false)
                            {
                                var arr = data.errors;
                                $.each(arr, function(index, value)
                                {
                                    if (value.length != 0)
                                    {
                                        $("#validation-errors").append('<div class="alert alert-danger"><strong>'+ value +'</strong><div>');
                                    }
                                });
                                $("#validation-errors").show(); 
                                btn.button('reset');                            
                            } else {
                                localStorage.login="true";
                                localStorage.email=email;
                                localStorage.id=id;

                                 window.location.href = 'user_profile.php';
                            }
                    },
                    error: function(xhr, textStatus, thrownError) {
                        alert('Something went to wrong.Please Try again later...');
                        btn.button('reset');
                    }
                });             
                return false;
            });
        });

    </script>

我想将这些值存储在本地存储中,但不知道如何执行此操作。

$uid;
$pic;
$fname;
$last_seen;

请告知。

2 个答案:

答案 0 :(得分:1)

我发现第一个错误是使用######################################################### layer0 = ConvLayer(input, filter_shape0) layer1 = ConvLayer(layer0.output, filter_shape1) layer2 = PoolLayer(layer1.output) layer3 = FCLayer(layer2.output.flatten(2), 4096) layer4 = DropoutLayer(layer3.output) Wb_params = layer3.params + layer1.params + layer0.params ######################################################### class ConvLayer(object): def __init__(self, inp, filter_shape, activation=RELU): input_shape = T.shape(inp) assert input_shape[1] == filter_shape[1] fan_in = np.prod(filter_shape) fan_out = np.prod(filter_shape[0], filter_shape[2:]) w_bound = np.sqrt(6. / (fan_in + fan_out)) w_values = np.asarray(RNG.uniform(low=-w_bound, high=+w_bound, size=filter_shape), dtype=theano.config.floatX) self.w = theano.shared(value=w_values, borrow=True) b_values = np.zeros(filter_shape[0], dtype=theano.config.floatX) self.b = theano.shared(value=b_values, borrow=True) conv_out = conv2d(input=inp, filters=self.w, filter_shape=filter_shape, input_shape=input_shape) self.out = activation(conv_out + self.b.dimshuffle('x', 0, 'x', 'x')) self.params = [self.w, self.b] class PoolLayer(object): def __init__(self, inp, pool_size=(2, 2)): self.out = pool.pool_2d(input=inp, ds=pool_size, ignore_border=True) self.params = None class FCLayer(object): def __init__(self, inp, num_hidden, activation=RELU): fan_in = T.shape(inp)[0] fan_out = num_hidden w_bound = np.sqrt(6. / (fan_in + fan_out)) w_values = np.asarray(RNG.uniform(low=-w_bound, high=+w_bound, size=(fan_in, fan_out)), dtype=theano.config.floatX) self.w = theano.shared(value=w_values, borrow=True) self.b = theano.shared(value=np.zeros(fan_out, dtype=theano.config.floatX), borrow=True) fc_out = T.dot(inp, self.w) + self.b self.out = activation(fc_out) self.params = [self.w, self.b] class DropoutLayer(object): seed_common = np.random.RandomState(0) layers = [] def __init__(self, inp, prob_drop=0.5): self.prob_drop = prob_drop self.prob_keep = 1.0 - prob_drop self.flag_on = theano.shared(np.cast[theano.config.floatX](1.0)) self.flag_off = 1.0 - self.flag_on seed_this = DropoutLayer.seed_common.randint(0, 2**31-1) mask_rng = RandomStreams(seed_this) self.mask = mask_rng.binomial(n=1, p=self.prob_keep, size=inp.shape) self.out = self.flag_on * T.cast(self.mask, theano.config.floatX) * inp + self.flag_off * self.prob_keep * inp DropoutLayer.layers.append(self) @staticmethod def setDropoutOn(): for i in range(0, len(DropoutLayer.layers)): DropoutLayer.layers[i].flag_on.set_value(1.0) @staticmethod def setDropoutOff(): for i in range(0, len(DropoutLayer.layers)): DropoutLayer.layers[i].flag_on.set_value(0.0) 是错误的:

使用localStorage 而不是window.localStorage.setItem("login",1);

然后使用localStorage.login ="true";

访问它

但是,在我看来,在window.localStorage.getItem("login");中存储类似会话(甚至也不是电子邮件地址)的东西也不是一个好主意,因为任何其他恶意应用程序都可以访问所有localStorage值, - 为什么不呢?首先在每个页面上执行单个ajax请求,以检查是否已建立有效会话,以及是否重定向到登录。在这种情况下,也不需要存储localStorage时间,会话和良好的身份验证应始终在服务器端完成。

答案 1 :(得分:0)

我们使用本地存储来存储某些值以供将来使用,它可以基于密钥覆盖该值。以下是商店值localStorage.setItem(“login”,1)的示例; 用于检索登录使用的值 localStorage.getItem( “登录”); 用于删除登录密钥使用 localStorage.removeItem( “登录”);

...谢谢