我需要在用户使用dnd插件移动jsTree中的节点后执行ajax调用。如果该ajax调用返回错误,我需要阻止移动发生,或者完全撤消操作。从move_node
事件监听器,有没有办法告诉dnd插件反转丢弃或以某种方式取消操作?我已尝试返回false
并设置e.preventDefault()
和e.stopImmediatePropagation()
,但似乎没有任何效果。
$($tree).jstree({
core: {
data: $treeData,
check_callback: function (op, node, parent, position, more) {
switch (op) {
case 'move_node':
// moveNode() validates the move based on
// some data stored in each node, but doesn't
// (and shouldn't) make an ajax call to determine
// if the node *actually can* be moved
return moveNode(node, parent, position, more);
}
}
},
plugins: ['dnd']
}).on('move_node.jstree', function(e, data) {
// moveNode() returned true and the user moved the node
if (!doMoveNode(data)) {
// none of this works!!
e.preventDefault();
e.stopImmediatePropagation();
return false;
}
});
答案 0 :(得分:0)
我想出来了......关键是在行动发生之前拦截行动,这可以在check_callback
中完成,因为:
function doMoveNode (node, parent) {
// tell the server to move the node
var nodeID = node.original.appData.id,
parentID = parent.original.appData.id,
success = false;
// make a non-async call to move the node
$.ajax({
url: move-product.php',
type: 'post',
async: false,
data: {
nodeID: nodeID,
parentID: parentID
},
dataType: 'json',
success: function (json) {
if (json.errorCode === 0) {
// this happens when the server was happy
success = true;
}
},
error: function (xhr) {
alert('an error occurred');
}
});
return success;
}
function moveNode (node, parent, position, more) {
// perform client-side validation to see if we can move node into parent
// just a demo, so always return true
return true;
}
$($tree).jstree({
core: {
data: $treeData,
check_callback: function (op, node, parent, position, more) {
switch (op) {
case 'move_node':
if (more && more.core) {
// this is the condition when the user dropped
// make a synchronous call to the server and
// return false if the server rejects the action
return doMoveNode(node, parent);
}
// return true if we can move, false if not
return moveNode(node, parent, position, more);
}
}
},
plugins: ['dnd']
}).on('move_node.jstree', function(e, data) {
// the move already happened
});