使用jquery将js变量传递给php
我试图将一个javascript变量发布到一个php文件中,非常简单 keyinput.php中的Jquery位:使用jquery将js变量传递给php,php,jquery,Php,Jquery,我试图将一个javascript变量发布到一个php文件中,非常简单 keyinput.php中的Jquery位: <script type="text/javascript"> var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>]; $(document).ready(function() { var img = document.getElementById("s
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($cat, $site)) ?>];
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).keydown(function (e) {
var key = e.which;
int rightarrow = 39;
int leftarrow = 37;
int random = 82;
if (key != rightarrow && key != leftarrow && key != random) {
return;
}
else {
//next image: right arrow
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
}
//last image: left arrow
if (key == leftarrow)
{
if (imgIndex == 0)
{
imgIndex = imgArray.length;
}
img.src = imgArray[--imgIndex];
}
//random: r
if (key == random)
{
imgIndex = Math.floor((Math.random()*(imgArray.length-1))+1);
img.src = imgArray[imgIndex];
}
}
$.post('./templates/viewcomic.php', {variable: imgIndex});
});
});
</script>
<?php
function getImages($catParam, $siteParam) {
include './scripts/dbconnect.php';
if ($siteParam == 'artwork') {
$table = "artwork";
}
else {
$table = "comics";
}
if ($catParam != null) {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table WHERE catidFK = $catParam");
}
else {
$catResult = $mysqli->query("SELECT id, title, path, thumb, catidFK FROM $table");
}
$img = array();
while($row = $catResult->fetch_assoc())
{
$img[] = "'" . $row['path'] . "'";
}
return $img;
}
?>
任何想法都会非常有用!我正在努力让我的漫画网站上线
谢谢 您的逻辑错误:在定义
键
变量时,e
未定义。然后将事件处理程序附加到一个if
语句中,该语句的计算结果总是为false,因此永远不会起作用
对键的赋值应该在事件处理程序中,条件必须在事件处理程序中
编辑:您还应该只在按下一个操作键(将其放入事件处理程序中)并对结果进行处理时执行ajax调用
编辑2:在上签出手册时,您应该添加一个回调函数来处理php脚本的返回值
例如:
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);
您希望在哪里看到输出?您正在做一篇AJAX文章,在$.post()
中没有success
处理程序。查看浏览器的网络控制台以查看响应。您是否尝试过在var周围加上单引号,如var imgIndex=''出于调试目的,最好执行var\u dump($\u POST)代码>并在浏览器的网络控制台中检查结果。@Jack是的,我试过了。它说“array empty”是您包含的keyinport.php破坏/操作$\u POST
超全局的吗?你的代码在我看来是正确的fix@Growler您仍然没有使用ajax函数的返回值。您能解释一下吗?我想我可以做一个简单的$.post(“我想调用的php文件”{variable:imgIndex}),并在php文件中捕获imgIndex javascript值。我已经尝试过了。“数据”最终包含php文件的所有html。但是数据应该包含javascript值Iwant@Growler然后,您应该确保您的脚本只输出您想要的javascript值。
$.post(
'./templates/viewcomic.php',
{ variable: imgIndex },
function(data) { /* data contains what you have echoed out in your php script */
alert(data);
}
);