gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:30:15 27 4
gpt4 key购买 nike

我还没有找到一个简单的单变量 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com