最近开始学习AJAX,我正在尝试制作评论部分,如前所见。 youtube,其中没有加载提交的评论所需的页面刷新。这是我到目前为止所得到的:
HTML:
<head><script src="JS/AJAX.js"></script>
<body>
<form method="post" action="">
User: <input type="text" id="name" /><br>
Comment:<br>
<textarea rows="5" cols="50" wrap="on" id="comment></textarea><br>
<button id="submit">Submit</button>
</form>
<h3>Comments go here:</h3>
<div id="commentarea"></div>
</body>
我不知道如何在不刷新页面的情况下将注释插入数据库。如果我使用let说的insert.php(将字段中的数据插入数据库)作为动作,它将刷新页面。
JS / AJAX(现在使用XMLHttpRequest();没有包含try和catch块来查找浏览器):function ajaxFunction(){
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById("commentarea").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET","fetch-data.php",true);
ajaxRequest.send(null);
}
PHP(取-data.php):
<?php
$con = mysql_connect("localhost","root","") or die(mysql_error());
$mysql_select_db('localh',$con);
$query = mysql_query("SELECT User, UserComment FROM content");
if(!$query){
die(mysql_error());
}
while($row = mysql_fetch_array($query)){
echo "<h3>".$row['User']."</h3>"."<br>";
echo "<p>".$row['UserComment']."</p>";
}
mysql_free_result($query);
mysql_close($con);
?>
单独加载或使用“include”表示提取过程有效。
据我按提交后的理解,它应该将注释和用户插入数据库。然后ajax应该使用fetch-data脚本来提取数据,然后将其添加到ID为“commentarea”的div中。我无法弄清楚这是如何工作的,更确切地说我是如何从表单中调用ajax函数的。
答案 0 :(得分:1)
你可以在action =“...”属性中调用javascript函数。如果该函数返回false,则表单不会通过常规的post请求提交,但是您可以使用输入数据作为ajax请求。