【发布时间】:2023-04-03 07:21:01
【问题描述】:
我正在使用 JavaScript 来处理我的表单提交和一个 Ajax 调用以仅刷新某个 div “不是整个页面”,表单提交成功但 div 内部的值没有不刷新。我已经尝试过堆栈溢出的其他方法/解决方案,但它们似乎都加载了整个页面,或者 div 的内容在表单提交时被隐藏了。
ajax.js
$(document).ready(function () {
$('.ajaxform').submit(function (e) {
e.preventDefault(); // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: "POST", // POST
dataType: 'html',
url: "info.php", // the file to call
cache: false,
success: function (response) { // on success..
$(".ld").load("info.php .ld"); //this hides the content of the div
// $('.ld').html(response);----This loads the entire page inside the div
}
});
return false; // cancel original event to prevent form submitting
});
});
info.php
<html>
<head>
</head>
<body>
<?php
...................
foreach($stmt as $obj){
$id = $obj['id'];
$likes = $obj['like1'];
echo '<form action="" method="post" id="ajaxform" enctype="multipart/form-data">';
echo '<input type="hidden" name="lkcv[]" value="'.$id.'">';
echo '<input type="hidden" name="like" value="">';
echo '<input type="image" src="images/like.png" id="lksub" width="15"
value="som" height="15" style="float:right;position:relative;
margin-right:290px;"/><div class="ld">'.$likes.'</div>';
echo '</form>’;
echo '<div id="emailform"></div>';
}
?>
</body>
</html>
我正在尝试刷新 div 标签内的变量“$likes”,而不刷新整个页面,现在我当前的代码在表单提交时隐藏了变量。我必须手动刷新才能查看对“$likes”的任何更改。
【问题讨论】:
-
ID 必须是 unqiue
-
@Andreas,我在我的表单中使用类和我想刷新的 div。
-
你想要 info.php 在你的 div 中还是只在其中生成 html?
-
在发布的
foreach循环中有三个ID,如果$obj中有多个元素,则会导致ID 重复 -
您将 XMLHTTPRequest 发送到整个文档而不是 PHP 的一部分(这就是您所需要的,因为我理解您的问题)。此外,您将请求发送到同一个当前页面,通过将 PHP 代码拆分为两部分来更好地分离关注点(一部分呈现初始表单,另一部分在处理表单时返回)
标签: javascript jquery html css ajax