【问题标题】:.How is it possible to set php session in ajax.如何在 ajax 中设置 php 会话
【发布时间】:2015-08-20 09:02:50
【问题描述】:

我有一个登录但无法设置 php 会话的 ajax。

如何在ajax中通过php设置会话?

我已经在标题中启动了会话,但是当下面的脚本运行时,它总是告诉我会话是真的。

    <script>
$(document).ready(function() {
    var loc=true;
    var php_var;
    // process the form
    $('#loginform').submit(function(event) {

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData2 = {
            'email'              : $('input[name=email]').val(),
            'password'           : $('input[name=password]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'http://example/api/v1/login', // the url where we want to POST
            data        : formData2, // our data object
            dataType: 'json',
            success: function(data){        
            console.log(data);      
                if(data.error){
                    //show error message here
                    $('#name-group').html('<p>'+data.message);  
                <?php $_SESSION['isloggedIn']=false;?>
                }else{

                    //handle success part       
                    $('#name-group').html('<p>Login Successful');
                    <?php $_SESSION['isloggedIn']=true;?>

                }               
              },
              error: function(jqXHR, textStatus, errorThrown){
                //request error 

                $('#name-group').html('<p>'+textStatus.message);
                console.log('jqXHR:');
                console.log(jqXHR);
                console.log('textStatus:');
                console.log(textStatus);
                console.log('errorThrown:');
                console.log(errorThrown);   
              }             
        });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});
</script>

【问题讨论】:

  • 刚刚注意到它是否正确:$('#name-group').html('&lt;p&gt;'+data.message);
  • 我没有找到任何可接受的答案
  • @jai 它返回 data.response .... 这不是错误
  • @MainakRay 我的意思是&lt;p&gt;+data.message,你不认为也应该关闭。

标签: php jquery ajax session


【解决方案1】:

您将客户端与服务器端代码混合在一起,php 代码在用户在浏览器中获取页面之前执行,因此就像您使用 api 执行此操作一样,对服务器上的 php 站点使用 ajax 请求并在那里设置会议。不要忘记session_start()

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 2012-01-31
    • 2015-04-07
    • 2016-03-12
    • 2018-04-04
    • 2016-01-29
    • 2015-08-18
    • 2018-09-05
    • 2018-10-30
    相关资源
    最近更新 更多