调用ajax函数时找不到请求的URL

时间:2013-12-07 11:22:42

标签: php mysql ajax

//我想通过调用js函数在数据库(MySql)中插入一个文本然后另一个js //脚本从数据库中检索数据并将其显示在我的html页面上的div中//来自// 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文件 // getdata.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页面中新//更新文本的部分将会显示 // enter code here谢谢我现在真是乱七八糟......请帮帮我......我是// @ ajax的新人...

1 个答案:

答案 0 :(得分:0)

<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 submit