我如何用innerhtml中的ajax和php更新mysql数据库

时间:2009-05-12 14:51:08

标签: php mysql database ajax

如何使用ajax和php更新mysql数据库而不刷新页面

3 个答案:

答案 0 :(得分:10)

以下是good example,它显示了SELECT语句,但它应该是直截了当的,并且很容易将脚本更新为您需要的内容。

示例页面中的HTML:

<html>
    <head>
        <script src="selectuser.js"></script>
    </head>
    <body>

        <form> 
            Select a User:
            <select name="users" onchange="showUser(this.value)">
                <option value="1">Peter Griffin</option>
                <option value="2">Lois Griffin</option>
                <option value="3">Glenn Quagmire</option>
                <option value="4">Joseph Swanson</option>
            </select>
        </form>

        <p>
        <div id="txtHint"><b>User info will be listed here.</b></div>
    </p>

</body>
</html>

<强> JavaScript的:

var xmlHttp;

function showUser(str)
{ 
    xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Request");
        return;
    }
    var url="getuser.php";
    url=url+"?q="+str;
    url=url+"&sid="+Math.random();
    xmlHttp.onreadystatechange=stateChanged;
    xmlHttp.open("GET",url,true);
    xmlHttp.send(null);
}

function stateChanged() 
{ 
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
        document.getElementById("txtHint").innerHTML=xmlHttp.responseText;
    } 
}

function GetXmlHttpObject()
{
    var xmlHttp=null;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        //Internet Explorer
        try
        {
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e)
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    }
    return xmlHttp;
}

由Ajax调用的PHP:

<?php
$q = $_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con) {
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("ajax_demo", $con);

$sql = "SELECT * FROM user WHERE id = '" . $q . "'";

$result = mysql_query($sql);

echo "<table border='1'>
    <tr>
    <th>Firstname</th>
    <th>Lastname</th>
    <th>Age</th>
    <th>Hometown</th>
    <th>Job</th>
    </tr>";

while ($row = mysql_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['FirstName'] . "</td>";
    echo "<td>" . $row['LastName'] . "</td>";
    echo "<td>" . $row['Age'] . "</td>";
    echo "<td>" . $row['Hometown'] . "</td>";
    echo "<td>" . $row['Job'] . "</td>";
    echo "</tr>";
}
echo "</table>";

mysql_close($con);

?>

答案 1 :(得分:5)

您可以使用JQuery库并执行类似

的操作
$.ajax({
   type: "POST",
   url: "some.php",
   data: "name=John&location=Boston",
   success: function(msg){
     alert( "Data Saved: " + msg );
   }
 });

在你的some.php文件中有这样的东西:

<?php

$name = $_POST['name'];
$location = $_POST['location'];

$query("your insert query");

$result = mysql_query($query);

?>

&GT;

答案 2 :(得分:1)