您好我正在使用关注方法保存div
的Javascript
$(document).ready(function(){
$( ".ex" ).draggable({containment:'parent',cursor:'pointer',opacity:0.6,
stop : function () {
var id = $(this).attr("id");
var x = $(this).position().left;
var y = $(this).position().top;
$.ajax({
url: "changeContact.php", /* You need to enter the URL of your server side script*/
type: "POST",
/* add the other variables here or serialize the entire form.
Image data must be URI encoded */
data:{
cid:id,
x: x,
y: y
},
success: function(msg)
{
}
})
}
});
});
PHP
$qry = "SELECT * from contact Where CustomerID='$pid'";
$result = mysql_query($qry);
while ($row = mysql_fetch_array($result))
{
echo '<div class="ex" id="'.$row["ContactID"].'">';
echo '</div>';
}
如何在页面上载时单独保存每个数据的位置?有没有什么方法可以自行调用Ajax方法而不拖动?
答案 0 :(得分:1)
我建议将执行AJAX调用的代码放入自己的函数中。这样,您可以在加载页面时调用它一次,也可以从可拖动代码中调用它:
$(function ($) { // $(function () ... is the same as $(document).ready(function () ... - just quicker
function doAjax (data) {
$.ajax({
url: 'changeContact.php',
type: 'POST',
data: data,
success: function () {
// ...
}
});
}
function onDraggableStop (event, ui) {
doAjax({
cid: this.id,
x: ui.offset.left,
y: ui.offset.top
});
}
function onPageLoad () {
var position = $(this).position();
doAjax({
cid: this.id,
x: position.left,
y: position.top
});
}
$( ".ex" )
.each(onPageLoad) // for all found elements: fire the ajax call immediately
// set up dragging support
.draggable({
containment: 'parent',
cursor: 'pointer',
opacity: 0.6,
stop : onDraggableStop // fire the ajax call for the element that just stopped dragging
}
);
});
答案 1 :(得分:0)
<强> [增订] 强>
在$.ajax()
之后添加$(document).ready(function() {
次请求:
$(document).ready(function(){
// additional ajaxrequest after pageload:
var obj = {windows:{}};
$(".ex").each(function() {
obj.windows[$(this).attr('id') + 'posLeft'] = $(this).position().left;
obj.windows[$(this).attr('id') + 'posTop'] = $(this).position().top;
})
$.ajax({
url : 'server.php',
type : 'post',
data : obj,
dataType : 'json',
success : function(data)
{
},
error : function()
{
}
});
$( ".ex" ).draggable({
//[...]
额外的$ .ajax()将在pageload之后执行。
例如,您的php脚本能够通过$_POST['windows']
获取数据。你可以使用foreach循环。
这是小提琴:http://jsfiddle.net/VQa3S/
以下是数据,将在我的小提琴中发送到服务器:
另外,请注意您的SQL查询。它可能会受到sql注入的攻击。使用PDO并绑定参数。