开发者

cannot print the array passed from javascript to php

here is the code.......here i am passing a javascript array to php... something is going wrong........

html:

    <html>
    <body onload="aa()" >
<script lan开发者_高级运维guage="javascript">
function aa()
{
var a, s;
a = [ 'one', 'two', 'three'];
s = JSON.stringify( a );
document.getElementById("fb_user").innerHTML= s;
}

    </script>
<form action="check1.php" method="post">
    <label id="fb_user"> </label>
<input type="submit" value="submit"/>
</form>
</body>
</html>

php code:

<?php

$fb_usr_id =json_decode(  $_POST['fb_user'], true );

    echo $fb_usr_id;
    ?>

when $fb_usr_id is echoed nothing is printed??


Contents of label tags are not submitted.

Try changing
<label id="fb_user"> </label> to
<input type="hidden" name="fb_user" id="fb_user">


    <html>
    <body onload="aa()" >
<script language="javascript">
function aa()
{
var a, s;
a = [ 'one', 'two', 'three'];
s = JSON.stringify( a );
document.getElementById("fb_user").value = s;
}

    </script>
<form action="check1.php" method="post">
<input type="hidden" name="fb_user" id = "fb_user" value="">
<input type="submit" value="submit"/>
</form>
</body>
</html>

On the backend do this first to check the validity of the posted variable as being json

var_dump( $_POST );


The contents of labels are not posted to the server. Instead, use <input type="hidden"> for inputs not intended to be editable by users:

<input name="fb_user" id="fb_user" type="hidden" />

Also, you should not change the innerHTML if you just want set the value of an input element. Instead, assign the aptly named value property.


Here is how you should do it:

<html>
    <body>
    <form action="check1.php" method="post">
        <label id="fb_users_list"></label>
        <input type="hidden" name="fb_user" id="fb_user" value="" />
        <input type="submit" value="submit"/>
    </form>
    <script type="text/javascript">
        (function(){
            var a, s;
            a = [ 'one', 'two', 'three'];
            s = JSON.stringify( a );
            document.getElementById("fb_users_list").innerHTML = s;
            document.getElementById("fb_user").value = s;
        })();
    </script>
    </body>
</html>

Please do not use body onload="", because you open up holes to XSS attack. Just put your script below your form, or better of at the end of the body, and you won't need an onload event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜