//我想通过调用js函数在数据库(MySql)中插入文本,然后另一个js//脚本从数据库中检索数据并将其显示在我的html页面上的div中//from//where我发布了文字....
//我提交要保存在数据库中的文本的 HTML
<html>
<head>
</head>
<body>
<div id = "change">Naruto</div>
<form id = "foo" action = "update()">
<input type = "text" name = "text" id = "text"/>
<input type = "submit" value = "change" ></input>
</form>
</body>
</html>
//单击按钮时调用的函数
<script>
function update()
{
$("#foo").submit(function(event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "acition.php",
type: "post",
data: values,
success: function(){
alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
}
</script>
//真正更新数据的php文件
<?php
mysql_connect("localhost","root","") or die ("CANNOT CONNECT TO THE DATABASE".mysql_error());
mysql_select_db("ajax_database") or die ("CANNOT CONNECT TO THE DATABASE");
$text = $_POST['text'];
$sql = "insert into news(statement)values('$text')";
mysql_query($sql);
?>
<html>
<head></head>
<body>
//从不同页面获取数据并将其显示到 html div 的脚本
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("change").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php",true);
xmlhttp.send();
</script>
</body>
</html>
//选择要从数据库检索数据的php文件 //获取数据.php
<?php
mysql_connect("localhost","root","") or die ("CANNOT CONNECT TO THE DATABASE".mysql_error());
mysql_select_db("ajax_database") or die ("CANNOT CONNECT TO THE DATABASE");
$sql = "select * from news";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result))
{
echo $rows[0];
}
mysql_close();
?>
//基本上就像我们更新facebook上的状态一样....我也在做同样的事情....//不刷新整个页面,它会刷新html页面中新的//更新文本的部分将显示
//在此处输入代码
谢谢,我现在真的一团糟......请帮助我......我是//ajax新手......
最佳答案
<form id = "foo">
<input type = "text" name = "text" id = "text"/>
<input type = "submit" value = "change" ></input>
</form>
删除操作属性并在 JavaScript 中
$("#foo").submit(function(event) {
event.preventDefault();
$("#result").html('');
$.ajax({
url: "action.php",
type: "post",
data: $(this).serialize(),
success: function(){
alert("success");
$("#result").html('Submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('There is error while submit');
}
});
});
您不需要在提交时调用任何函数,因为您已经在使用jquery提交
关于php - 调用ajax函数时找不到请求的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20440753/