Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - Make div text change on click based on PHP data using Ajax

Let's say I have in a PHP file a div called myDiv, an image called myImg, and a PHP variable called $x. When someone clicks on myImg, I need myDiv's text to change based on the value of $x.

For example, let's say I want myDiv's text to change to "Hello" if $x==1, and to "Bye" if $x==2.

Everytime the text changes, the value of $x will change too, in this case, let's say if $x==1 when myImg is clicked, then $x's value will become 2($x=2), and viceversa.

I'm using jQuery, but I read that I need to use Ajax too for this (To check on the server the value of $x), but I can't figure out how to do it. I read about Ajax, but none of the examples explains something like this.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'll add the revised solution in a new answer so you can still see the earlier examples as the code may provide useful examples.

In this example, we use a session variable to store the value between ajax calls.

FILE1.php

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function(){
        $('#myImg').click(function() {
            $.ajax({
                type: "POST",
                url: "FILE2.php",
                data: '',
                success:function(data){
                    alert(data);
                }
            });
        });
    });
</script>

<div id="myDiv">
    Click picture below to GO:<br />
    <img id="myImg" src="http://www.gravatar.com/avatar/783e6dfea0dcf458037183bdb333918d?s=32&d=identicon&r=PG">
</div>

FILE2.php

<?php
session_start();

if (isset($_SESSION['myNum'])) {
    $x = $_SESSION['myNum'];
}else{
    //No session set yet, so initialize with x = 1
    $x = 1;
}

if ($x == 1) {
    $_SESSION['myNum'] = 2;
    echo 'Hello its a one';
}else{
    $_SESSION['myNum'] = 1;
    echo 'Goodbye TWO';
}
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...