开发者

Pass javascript variable by jquery

index.php

<script type="text/javascript">
    document.write(lastmsgID); // fail display the value (my problem is here, please help)
        function myfunction()
        {
            jQuery.get("usermessage.php, function(data) {
               document.write(lastmsgID); //success display the value
            });
        };
</script>

usermessage.php

<?php $latestmsgid= "lovelovelove";
echo("<script type='text/javascript'>\n"); // pass php varible to javascript global variable lastmsgID
echo("lastmsgID = '". $latestmsgid  ."';\n");
echo("</script>"); 
?>

From my codes above, I declare global javascript variable lastmsgID on usermessage.php file. Then I used jQuery.get get the value of variable. Now my problem is I can only get the variable value inside myfunction() function, how can I pass the value of variable from the function to outside the function?

Update:

<script type="text/javascript">
        function myfunction()
        {
            jQuery.get("usermessage.php, function(data) {
               var test=data
               document.write(test); //success display the value
            });
        };

        document.writ开发者_如何学运维e(test); // fail display the value because it is outside the function. (my problem is here, please help)
    </script>


usermessage.php contains an HTML <script> object, but index.php never does anything with the HTML it receives back from the AJAX call (data). You'd have to append the received HTML to the primary DOM.

Instead I recommend that usermessage.php returns the lastMsgID in plain text (or JSON), and then you have that in the variable data.

Update

You have since stated a requirement to access the retrieved value from the enclosing scope. Do this by creating a variable that's "more global", and setting its value accordingly:

<script type="text/javascript">
    var MyVariable = ''; // global variable: changes to it will be global too

    function myfunction() {
        jQuery.get("usermessage.php, function(data) {
           MyVariable = data;
        });
    };

    document.write(MyVariable);
    /* ^ this will work, but not quite here. it'll show you the value
       ONLY if you write this line somewhere so that it executes *after*
       the jQuery.get call has completed. */
</script>


PHP

<?php
$latestmsgid = Array("id" => "lovelovelove");
echo json_encode($lastmsgid);
?>

JS

var ID;

$.getJSON("usermessage.php", function(json) {
    ID = json.id;
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜