将值从jquery传递给php

时间:2015-02-09 18:16:02

标签: php jquery ajax

如果这是重复,我很抱歉,但我已经在互联网上搜索了一个解决方案。我想知道如何将以下代码传递给php

           setTimeout(function () {
                // did it win??!?!?!
                var spin = _this.cache.wheelPos,
                    degrees = spin % 360,
                    percent = (degrees / 360) * 100,
                    segment = Math.ceil((percent / 6)),  //divided by number of segments
                    win = _this.cache.wheelMapping[segment - 1]; //zero based array

                console.log('spin = ' + spin);
                console.log('degrees = ' + degrees);
                console.log('percent = ' + percent);
                console.log('segment = ' + segment);
                console.log('win = ' + win);

                //display dialog with slight delay to realise win or not.
                setTimeout(function () {
                    alert('you won '+win+'!');
                }, 700);

我试过了

    setTimeout(function () {
                        $.ajax({
   url: 'test.php',
   type: 'post',
   data: {"win" : +win},
   success: function(data) {
   }
});
}, 700);

我正在通过将其写入文本文件来测试它 php文件是:

<?php


$_SESSION['test'] = (isset($_POST['win']) ? $_POST['win'] : "";

if (empty($_SESSION['test']){
echo "nothing here";
}else{
$var = $_SESSION['test'];
file_put_contents("test.txt", $var . "\n", FILE_APPEND);
exit();
}
?>

在意识到我没有在函数中放任何东西后我设置了一个警告,显示以下错误

<br />
<b>Parse error</b>:  syntax error, unexpected ';' in <b>/home/thegrpg/public_html/grpg/test.php</b> on line <b>4</b><br /> 

2 个答案:

答案 0 :(得分:0)

您的数据似乎不是数组。 试试

$.ajax({
 url: 'test.php',
 type: 'post',
 data: [{"win" : +win}]
});

答案 1 :(得分:0)

(将我的所有评论转换为答案)

首先要访问我们需要在PHP页面的to中调用session_start();的会话。然后,)

的分配缺少结束$_SESSION['test']
<?php
session_start();

$_SESSION['test'] = (isset($_POST['win']) ? $_POST['win'] : "");
/*                                                            ^ here */
...
?>

然后在AJAX调用中,我们要从+中删除+win。所以改变它:

data: {"win" : +win},

要:

data: {"win" : win},