如何将输入值传递给PHP?更新2016-08-02

时间:2016-08-01 22:05:02

标签: php jquery html ajax

我在代码中找不到问题... PS当我在won.php中更改 $ wonorlose 时,将lost.php更改为任何数字如果我把它更改为 $ wonorlose = $ _GET [&#39; wonorlose&#39;]; ,那么我的输入值将无法正常工作:/ < / p>

这是我的所有系统:

dice.php (主要php):

<?php
session_start();
include_once 'dbconnect.php';
if(!isset($_SESSION['user']))
{
 header("Location: /manopuslapis/index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<br>
<h3 id="satoshitext" align="center">Money: <?php echo $userRow['money'];
?></h3>
<br>
</form>
<script>
function rollTail(){
    var die1 = document.getElementById("die1");
    var status = document.getElementById("status");
    var d1 = Math.floor(Math.random() * 2) + 1;
    if(d1 == 1)
    {
    die1.innerHTML = "You won!";
    fliped.innerHTML = "Fliped Tail!";
    var ajax = new XMLHttpRequest();
    ajax.open('POST','won.php',true);
    ajax.send();
    }
    else if (d1 == 2)
    {
    die1.innerHTML = "You lose!";
    fliped.innerHTML = "Fliped Head!";
    var ajax = new XMLHttpRequest();
    ajax.open('POST','lose.php',true);
    ajax.send();
    }
}
function rollHead(){
    var die1 = document.getElementById("die1");
    var status = document.getElementById("status");
    var d1 = Math.floor(Math.random() * 2) + 1;
    if(d1 == 1)
    {
    die1.innerHTML = "You lose!";
    fliped.innerHTML = "Fliped Tail!";
    var ajax = new XMLHttpRequest();
    ajax.open('POST','lose.php',true);
    ajax.send();
    }
    else if (d1 == 2)
    {
    die1.innerHTML = "You won!";
    fliped.innerHTML = "Fliped Head!";
    var ajax = new XMLHttpRequest();
    ajax.open('POST','won.php',true);
    ajax.send();
    }
}
</script>
<div id="fliped" class="fliped"> </div>
<div id="die1" class="dice"> </div>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<button id="Head" onclick="rollHead()">Head</button>
<button id="Tail" onclick="rollTail()">Tail</button>
<br>
<br>
<br>
<h2 align="center"><form method="get" >
<input type="text" id="wonorlose" name="wonorlose" value=50>
</form>
</h2>
</body>
</html>

won.php

<?php
session_start();
include_once 'dbconnect.php';

if(!isset($_SESSION['user']))
{
 header("Location: /manopuslapis/index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);

$wonorlose = $_GET['wonorlose'];
echo $wonorlose;
mysql_query("UPDATE `users` SET money=money+'$wonorlose' WHERE user_id=".$_SESSION['user']); 
?>

lose.php

<?php
session_start();
include_once 'dbconnect.php';

if(!isset($_SESSION['user']))
{
 header("Location: /manopuslapis/index.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);

$wonorlose = $_GET['wonorlose'];
echo $wonorlose;
mysql_query("UPDATE `users` SET money=money-'$wonorlose' WHERE user_id=".$_SESSION['user']);  
?>

3 个答案:

答案 0 :(得分:0)

您正在尝试读取未发送的值。 $_GET的变量为passed in the URL query string。因此,您希望从JavaScript访问网址lose.php?wonorlose=whatever。可以使用$("wonorlose").val();来访问它,假设它具有该ID。

答案 1 :(得分:0)

在您的第1页

中尝试此来源
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

</head>
<body>
    <h2 align="center">
            <input type="text" name="wonorlose" value=50>
            <button id="Tail" onclick="dowhatever()">Tail</button>
    </h2>
    <script type="text/javascript">
        function dowhatever(){
            var ajax = new XMLHttpRequest();
            ajax.open('POST','jsOnChange.php',true);
            ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            var wonorlose = document.getElementsByName("wonorlose")[0].value;
            ajax.send("wonorlose="+wonorlose);
        }
    </script>
</body>
</html>

您将在Firebug中看到此结果

enter image description here

lose.php我的案例中jsOnChange.php

使用echo $_POST['wonorlose']; //For testing

答案 2 :(得分:0)

我有一个半小时的备用,所以我很快把它放在一起,希望它可以帮助解决你的问题。可能存在允许用户指定诸如value或奖品之类的问题的问题,因此应该在服务器端处理这些问题。此代码填充会话变量以跟踪奖金等,并发送回ajax回调的json数据 - 这只是例如〜

<?php
    session_start();

    if( $_SERVER['REQUEST_METHOD']=='POST' ){

        ob_clean();

        if( !isset( $_SESSION['coins'] ) ) $_SESSION['coins']=array('attempts'=>0,'total'=>0);

        $_SESSION['coins']['total'] += $_POST['prize'];
        $_SESSION['coins']['attempts']++;

        $_POST['total']['total']='£'.$_SESSION['coins']['total'];
        $_POST['total']['attempts']=$_SESSION['coins']['attempts'];

        /*
            -----------------------
            Example db and sql code
            -----------------------
            $host   =   'localhost';
            $uname  =   'root';
            $pwd    =   'xxx'; 
            $db     =   'xxx';

            $db=new mysqli( $host, $uname, $pwd, $db );
            $sql='update `users` set `money`=? where `user_id`=?;';

            $stmt=$db->prepare( $sql );
            $stmt->bind_param( 'is', $_POST['prize'], $_SESSION['user'] );
            $res=$stmt->execute();
            $db->close();
            $db=null;
        */

        header('Content-Type: application/json');
        exit( json_encode( $_POST ) );
    }
?>
<!doctype html>
<html>
    <head>
        <title>CoinToss Game</title>
        <script type='text/javascript' charset='utf-8'>
            function tosscoin(e){
                var i,msg,result;

                var prize=parseFloat( document.getElementById('wonorlose').value );
                var results=document.getElementById('results');

                var el=e.target;
                var type=el.dataset.type;
                var i = getrandom(0,1);

                msg=( i==1 ? 'You won' : 'You lost' );
                prize=( i==1 ? prize : prize * -1 );

                switch( type ){
                    case 'heads':
                        result=( i==1 ? 'Flipped Heads!' : 'Flipped tails!'  );
                    break;
                    case 'tails':
                        result=( i==1 ? 'Flipped Tails!' : 'Flipped heads!' );
                    break;
                }
                ajax.call( this, 'post', location.href, { i:i, prize:prize, result:result, msg:msg, type:type }, cbcointoss,{ target:results } );
            }

            function cbcointoss(r,o,h){
                var json=JSON.parse(r);
                o.target.innerHTML=[json.msg+' '+json.result,json.total.total].join(', ');
            }

            function getrandom(min,max){
                return Math.floor( Math.random()*( max-min +1 ) + min );
            }

            function ajax(m,u,p,c,o){
                /*
                    Method,Url,Params,Callback,Options
                */
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }

            function bindEvents(){
                var col=document.querySelectorAll('input[type="button"]');
                if( col ){
                    for(var n in col)if(col[n].nodeType==1){
                        col[n].addEventListener('click',tosscoin,false);
                    }
                }
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents, false );
        </script>
        <style type='text/css' charset='utf-8'></style>
    </head>
    <body>
        <form name='cointoss' method='post'>

            <input type='button' data-type='heads' value='Heads' />
            <input type='button' data-type='tails' value='Tails' />
            <input type="text" id="wonorlose" name="wonorlose" value=50>

            <span id='results'></span>
        </form>
    </body>
</html>