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

标签 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
?>

我将如何在不刷新页面的情况下发布和发送此信息? AJAX 真的让我感到困惑,所以如果有一个可行的实现让我开始这样做就太好了,非常感谢。

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

最佳答案

要使用 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
?>

关于javascript - Ajax - 问题 - 将 JavaScript Var 发送到 PHP 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427472/

相关文章:

Javascript 对象问题

PHP。如何从 2 个 mysql 表而不是 1 个表中获取数据

php - 使用 xpath 查找节点

javascript - jQuery 向上/向下滑动效果不适用于 div

javascript - 检测用户设备并在 js/jquery 中分配不同的 jquery(桌面/移动(ipad))?

javascript - setCustomValidity() 在 Chrome 浏览器中不起作用

javascript - jquery 数据表排序插件根本不起作用

javascript - 菜单粘贴触发了哪个事件?

javascript - 问题: The whole page loading instead just the div with .加载()

php - 如何使用php条件语句查询mysql表并显示结果