请在点击格文本变化的基础上使用Ajax PHP数据 [英] Make div text change on click based on PHP data using Ajax
问题描述
让我们说我有一个PHP文件名为 myDiv
DIV, myImg
称为图像,和PHP变量名为 $ X
。
当有人点击 myImg
,我需要 myDiv的
文本以更改基于 $的价值X
。
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
.
例如,让我们说,我想 myDiv的
文本更改为你好
如果 $ X == 1
,以及再见
如果 $ X == 2
。
For example, let's say I want myDiv's
text to change to "Hello"
if $x==1
, and to "Bye"
if $x==2
.
每当文本的变化, $ X值
也可能发生变化,在这种情况下,我们说,如果 $ X == 1
在 myImg
点击,然后 $ X的
值将成为 2
($ 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.
我用的jQuery
,但我读了我需要使用阿贾克斯
过这个(要检查在服务器上的 $的X
)的值,但我无法弄清楚如何做到这一点。我读阿贾克斯
,但没有一个例子说明了这样的事情。
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.
推荐答案
我将添加一个新的答案修改后的解决方案,所以你仍然可以看到前面的例子为code可提供有用的例子。
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.
在这个例子中,我们使用一个会话变量来存储AJAX调用之间的值。
In this example, we use a session variable to store the value between ajax calls.
FILE1.php
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
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';
}
?>
这篇关于请在点击格文本变化的基础上使用Ajax PHP数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!