使用Ajax查询数据库

时间:2015-10-10 11:53:46

标签: javascript php jquery ajax database

我想从JavaScript函数中检查我的数据库。我以前从未这样做过,我似乎无法弄明白。我不知道这是不是正确的方法,但它是我找到的那个。这是我简单的HTML:

<!doctype html>
<html>
<head>
    <script src="Test.js"></script>
</head>
<body >
<p><a href="#" onClick="start();">Click me</a></p>
</body>

JavaScript:

function start(){
    $.ajax({
        type: "POST",
        url: "checkDatet.php",
        datatype: "html",
        data: {functionname: 'Name', arguments: ['John']},
        success: function(data) {
            alert(data);
        }
    });
}

PHP:

<?php
function familyName($name1) {
    $username = "user";
    $password = "pass";
    $hostname = "localhost";
    $output ="AAA";
    $dbhandle = mysql_connect($hostname, $username, $password)
        or die("Unable to connect to MySQL");
    $selected = mysql_select_db("databasee", $dbhandle)
        or die("Could not select database 'databasee'");
    $names = mysql_query("SELECT name WHERE name1 = '$name'");
    if($row = mysql_fetch_assoc($names)){
        $data = $row{'name'};
        if($data <> null)
            $output= "found it";
        else
            $output= "havent found it";
    }
    echo $output;
}
?>

2 个答案:

答案 0 :(得分:2)

实际上没有任何东西可以调用你的功能!这样做:

function start(){
    $.get('checkDatet.php?name=John', function(data) {
        alert(data);
    }
});

然后在“checkDatet.php”中你需要调用你的函数:

<?php
familyName($_GET['name']);

function familyName($name1) {
$username = "user";
$password = "pass";
$hostname = "localhost";
$output ="AAA";
$dbhandle = mysql_connect($hostname, $username, $password)
    or die("Unable to connect to MySQL");
$selected = mysql_select_db("databasee", $dbhandle)
    or die("Could not select database 'databasee'");
$names = mysql_query("SELECT name WHERE name1 = '$name'");
if($row = mysql_fetch_assoc($names)){
    $data = $row{'name'};
    if($data <> null)
        $output= "found it";
    else
        $output= "havent found it";
}
echo $output;
}
?>

答案 1 :(得分:2)

你调用一个文件,并且你没有调用该函数,所以只需改变你的php代码

<?php
    $username = "user";
    $password = "pass";
    $hostname = "localhost";
    $output ="AAA";
    $name = $_POST['name'];
    $dbhandle = mysql_connect($hostname, $username, $password)
        or die("Unable to connect to MySQL");
    $selected = mysql_select_db("databasee", $dbhandle)
        or die("Could not select database 'databasee'");
    $names = mysql_query("SELECT name WHERE name1 = '$name'");
    if($row = mysql_fetch_assoc($names)){
        $data = $row{'name'};
        if($data <> null)
            $output= "found it";
        else
            $output= "havent found it";
    }
    echo $output;

?>