我试图提交一个表单,并根据AJAX和PHP的表单提交加载数据。我希望在不重新加载页面的情况下完成此操作。
<<p> html/php/strong><form method="POST">
<button type="submit" name="image1">
<button type="submit" name="image2">
<button type="submit" name="image3">
<button type="submit" name="image4">
</form>
<div>
// content gets loaded into here
</div>
jquery $("form").submit(function(event) {
event.preventDefault();
$("div").load("content-load.php");
}
content-load.php
$validInputs = array('image1', 'image2', 'image3', 'image4');
foreach ($validInputs as $v) {
if(isset($_POST[$v])){
// load content associated with image1, or image2, etc, into Div
}
}
是的,"event.preventDefault()"是防止页面刷新的好方法。但是它实际上并没有提交表单!我需要提交的表单,因为我加载到Div的内容是依赖于"$_POST[$v]"被设置。根据用户是单击了第一个、第二个、第三个还是第四个提交按钮,content-load.php将循环执行$validInputs并确定按下了哪个按钮。根据点击哪个按钮,将加载特定的内容。
如果我使用ajax和prevent default,上面的代码将永远不会运行,因为表单被阻止提交。php需要遍历数组并确定哪个按钮被按下了——但是由于event.preventDefault,没有按钮被按下!我如何让php检测哪个按钮是"设置"不使用页面刷新?
当您使用event.preventDefault();
内部处理程序时,它会取消表单提交操作。如果你想在不刷新页面的情况下提交表单,更好的方法是使用$.ajax
, $("div").load("content-load.php");
应该放在成功回调中。
如果您使用的是Jquery,那么$。帖子是你的朋友。
的例子:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});
进一步阅读:http://api.jquery.com/jquery.post/