通过jQuery的AJAX调用PHP的SessionID
问题描述:
JS 在(start.php)
JS in (start.php)
$(document).ready(function()
{
$('#btn_1').click(function(){
$.ajax({
type: "POST",
url: "get_data.php,
data: 'func=getData1',
success: function(msg){
$('#div_1').html(msg);
}
});
$('#div_1').show();
})
});
PHP (somename.php)
PHP (somename.php)
<?php
session_start();
if(trim($_POST['func']) == "getData1")
{
echo "Test";
}
?>
我如何可以通过从start.php的SessionID通过我的ajax到get_data.php文件? 而如何可以通过完整的URLURL:get_data.php,给JS-文件,这样我就可以切换了PHP的文件,应该从阿贾克斯名为
How can i pass the sessionid from start.php through my ajax to the get_data.php file ? And how can pass the complete URL "url: "get_data.php," to the js-File so that i can switch the php-files, that should be called from ajax ?
答
存储会话ID
的JavaScript变量,并通过Ajax调用发送,像这样的:
Store Session ID
in javascript variable and send it through ajax call, like this:
var session_id = '<?php echo session_id();?>';
完成code应该是:
Complete code should be:
var data = {func:'getData1',session_id:session_id};
$('#btn_1').click(function(){
$.ajax({
type: "POST",
url: "get_data.php",
data: data,
success: function(msg){
$('#div_1').html(msg);
}
});
$('#div_1').show();
})
更新
如果您要访问的PHP变量的外部js文件,其中包括js文件之前定义的变量。像:
Updates
If you want to access php variable in external js file, define variable before including js file. Like:
<script type="text/javascript">
var session_id = '<?php echo session_id();?>';
</script>
<script src="./ajax.js" type="text/javascript"></script>