jQueryAJAX函数设置一个PHP$_SESSION变量,单个复选框


jQuery AJAX function to set a PHP $_SESSION variable, single checkbox

我第一次使用Ajax。我试图捕获单个复选框的值,如果选中,则将PHP$_SESSION变量设置为true。

在HTML中,我有这个。

 <input type="checkbox" name="agree" id="agree"/>
and the js is this....not sure what to put in the AJAX data params??
    $(document).ready(function() {
            $('#agree').click(function(){ 
                $.ajax({
                    url: 'agree.php',
                    type: 'GET',
                    data: { agreement:"checked" } //NOT Sure ABout this??
                });      
        })
    });

和PHP,伪代码可能是因为它不起作用。。

if($_GET['agreement'] == 'checked') {
$_SESSION['hm-agreement'] = true;
     } else {
$_SESSION['hm-agreement'] = false;

}

AJAX调用看起来不错。也许您应该在PHP脚本中添加一些调试,并使用Firebug或其他开发工具进行查看。

不要忘记在PHP脚本的开始处使用start_session()。如果您放弃了此调用,则会话对象不存在。

您将需要检查装箱是否已选中,无论您向php文件发送什么,您的代码现在都会将会话变量设置为true。

还使用了get与ajax的简写,更少的代码

HTML

<input type="checkbox" name="agree" id="agree"/>

JS-

$(document).ready(function() {
    $('#agree').click(function(){ 
        $.get('agree.php','agreement=' + ( this.checked ? 1 : 0 ) });
    })
});

PHP

session_start();
if($_GET['agreement']) {
    $_SESSION['hm-agreement'] = true;
} else {
    $_SESSION['hm-agreement'] = false;
}