[英]Passing javascript variable to php without refreshing the page
I have a 5x5 grid of div boxes (25 of them) and I am using jQuery UI to register when I drop a item in it. 我有一个5x5的div框网格(其中有25个),当我在其中放置项目时,我正在使用jQuery UI进行注册。 It will receive the title of the box it was dropped in and the name of the item, that part works. 它将收到它放入的盒子的标题和该部分起作用的物品的名称。
I want to pass the title and name to PHP without refreshing the page (because then the items will reset). 我想在不刷新页面的情况下将标题和名称传递给PHP(因为项目将重置)。 I get a "success!" 我得到“成功!” but it seems like it doesn't pass the data. 但似乎没有传递数据。
index.php 的index.php
<script>
$(function() {
$( "li img" ).draggable({
snap: ".grid",
start: function (event, ui ) {
item = $(this).attr('title');
}
});
$( "li .grid" ).droppable({
drop: function( event, ui ) {
box = $(this).attr('title');
$.ajax({
type: "POST",
url: 'index.php',
data: { box : 'box' },
success: function(data){
alert("success!");
}
});
}
});
});
</script>
sessions.php sessions.php
<?php
session_start();
if(isset($_POST['box']))
{
// store session data
$_SESSION['box'] = $_POST['box'];
}
//retrieve session data
echo $_SESSION[box];
?>
How do I pass the title and name to PHP without refreshing the page? 如何在不刷新页面的情况下将标题和名称传递给PHP?
Try to change the url
and your data
from this: 尝试从中更改url
和您的data
:
url: 'index.php',
data: { box : 'box' }
to this: 对此:
url: 'sessions.php',
data: { box : box }
Given that you're doing this... 鉴于您正在这样做...
box = $(this).attr('title');
I assume you want to pass that variable to the server. 我假设您想将该变量传递给服务器。 However, you're just passing the literal string "box"
, not the variable box
. 但是,您只是传递文字字符串"box"
,而不是变量box
。
In your code, you've written this... 在您的代码中,您已经编写了此代码...
data: { box : 'box' },
which needs to be this, to pass the value in box
: 需要这样,以传递box
的值:
data: { box : box },
As an aside, you've created a global variable box
. 顺便说一句,您已经创建了一个全局变量box
。 Instead of box = $(this).attr('title');
而不是box = $(this).attr('title');
, you should use var box = $(this).attr('title');
,则应使用var box = $(this).attr('title');
to create a variable local to the function. 在函数本地创建一个变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.