Ajax - 问题 - 将JavaScript Var发送到PHP脚本

时间:2015-10-30 01:24:30

标签: javascript php jquery ajax

我无法找到一个带有单个变量的ajax的简单示例,这里的所有内容对于AJAX初学者来说都太复杂了。我已经观看了关于这个主题的4个不同的YouTube视频,但似乎无法做到正确。 我有一个像src的图像在一个变量中,如此使用JavaScript ..

<img alt="" src="blah.jpg" style="height: 276px; width: 200px" id="imgClickAndChange1" onclick="changeImage(this)" />

<script language="javascript">
function changeImage(imagePass) {

var num = Math.floor((Math.random() * 48) + 1);
var n = num.toString();
var numImg = n.concat(".jpeg");
var string = "/Images/Folder/"
var final = string.concat(numImg);
imagePass.src = final;
//(this is where I want to pass the variable imagePass.src or "final" to a php script w/ Ajax)

这是我的php脚本:

<?php>
include_once "code.php";  //connecting to database
$s = (this is where I want the variable to be posted);
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) "  //Making a row in my database w/ the id of the variable add 1 to the count
?>

我如何发布并发送这个w / out页面刷新? AJAX真让我感到困惑,所以一个工作实现让我开始这个很棒,非常感谢。

//让我们假设脚本所在的php页面名为'hello.php'

1 个答案:

答案 0 :(得分:2)

要使用ajax,请尝试以下方法:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">

function changeImage(imagePass) {

        var num = Math.floor((Math.random() * 48) + 1);
        var n = num.toString();
        var numImg = n.concat(".jpeg");
        var string = "/Images/Folder/"
        var final = string.concat(numImg);
        imagePass.src = final;
        $.ajax({
          url : 'hello.php',
          type: 'post',
          data : {'final':final},
          success: function()
              {
                    alert('Success!');
              }
      });
   }
</script>

PHP脚本(hello.php):

<?php>
include_once "code.php";  //connecting to database
$s = $_POST['final'];
$temp = explode('/', $s);
$temp2 = explode('.', $temp[count($temp) - 1]); //this is getting the variable I want from the variable sent(which is actually a number)
$float = (int)$temp2; //changing the number (which is a string) to an int
mysql_query("UPDATE Variable SET `upVote` = `upVote`+1 WHERE id= (variable here)) "  //Making a row in my database w/ the id of the variable add 1 to the count
?>