gpt4 book ai didi

javascript - 使用ajax刷新div内容

转载 作者:行者123 更新时间:2023-11-28 07:07:00 25 4
gpt4 key购买 nike

我使用 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”的任何更改。

最佳答案

您正在将 XMLHTTPRequest 发送到整个文档而不是 PHP 的一部分(据我从您的问题中了解到,您需要的是后者)。此外,您将请求发送到同一当前页面 info.php,最好通过将 PHP 代码拆分为两部分(呈现初始表单的部分和呈现初始表单的部分)来分离问题。旨在在服务器端处理它)。

因此,AJAX 将返回 info.php 的所有结果(静态标记+生成标记),并返回所有最终 HTML 并将其加载到 .ld

我建议创建两个文件:form.phpprocess-form.php。当 form 返回文档时,将执行您的 AJAX 调用.php准备就绪,并将被发送到 process-form,该表单将在处理表单后返回所需的数据。

这应该可以在不刷新页面的情况下工作(使用 AJAX 的主要目的)。

关于javascript - 使用ajax刷新div内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31628161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com