我在做什么:
我正在附加一个带有表单和一些按钮的div。两个按钮是保存和取消。当点击保存时,我发布表单并获得响应。我想要替换保存的旧div点击。
这是html和jquery http://jsfiddle.net/thiswolf/vSnJJ/1/
我正在使用这个php,但是帖子数据因为它的一个例子而没有被清理
<?php
/**
test if replaced item can post and be deleted
@move ---->next
*/
$sliderKey = $_POST['sliderKey'];
$sliderPosition = $_POST['sliderPosition'];
$sliderTitle = $_POST['sliderTitle'];
$sliderLocation = $_POST['sliderLocation'];
$sliderDescription = $_POST['sliderDescription'];
$uniqid = uniqid();
echo "<div class='krudItem' id='$uniqid'><form class='aj' name='itemForm' method='post'action=''><section><label>Slider Title</label><input type='hidden' name='sliderKey' value='$sliderKey'/><input type='hidden' name='sliderPosition' value='$sliderPosition'/><input type='text' name='sliderTitle' value='$sliderTitle'/></section><section><label>Slider Location</label><input type='text' name='sliderLocation' value='$sliderLocation'/></section><section><label>Slider Description</label><textarea name='sliderDescription'>THIS IS THE REPLACEMENT</textarea></section><button name='saveNew' class='saveNew' id='$uniqid'>save</button><button name='newCancel'>delete</button></form></div>";
?>
这是我正在使用的整个jquery
jQuery(function() {
function randString(n)
{
if(!n)
{
n = 5;
}
var text = '';
var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for(var i=0; i < n; i++)
{
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
$("#button").click(function () {
$("<div class='krudItem' id='xxx'><form class='aj' name='itemForm' method='post' action=''><section><label>Slider Title</label><input type='hidden' name='sliderKey' value='16'/><input type='hidden' name='sliderPosition' value='12'/><input type='hidden' name='clickedButton' value='initial'/><input type='text' name='sliderTitle' value='lorem'/></section><section><label>Slider Location</label><input type='text' name='sliderLocation' value='ipsum'/></section><section><label>Slider Description</label><textarea name='sliderDescription'>hello world</textarea></section><button name='saveNew' class='saveNew' id='buttonId' value='saveNew'>save</button><button name='newCancel'>cancel</button></form></div>").appendTo('.krudSpace');
});
//save new
jQuery('.saveNew').live("click",function(event)
{
jQuery(this).attr("id",randString(7));
event.preventDefault();
var contentPanelId = jQuery(this).attr("id");
jQuery.ajax({
type: "POST",
url: "insert.php",
data: jQuery(".aj").serialize(),
success: function(data){
var quoted = "#"+contentPanelId;
jQuery(quoted).replaceWith(data)
}
});
return false;
});
});
它在某种程度上起作用,但旧的div根本没有被替换,但响应被附加在旧的下方。
答案 0 :(得分:1)
你让事情变得困难。只需保存父本身:
var $p = jQuery(this).parent();
并且做:
$p.replaceWith(data)
这是一个更新的jsFiddle(它使用error
而不是success
,因为没有PHP):http://jsfiddle.net/vSnJJ/2/。