1

所以我需要做的就是使用 ajax 从文本框中获取名称,将其提交给 php 脚本,然后打印 php 的结果。

这是我到目前为止所拥有的:

<form action="" method="POST">
    Are you in the deathnote? <br/>
    Name: <textarea type="text" name="checkname"></textarea> 
    <input type="submit" value="Submit" onclick="namecheck()">
</form>
<div id="coddisp"> Nothing yet </div>

这是我拥有的ajax:

<script>
function namecheck() {
    var xmlhttp;
    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else { // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("coddisp").innerHTML = xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET", "check.php", true);
    xmlhttp.send();
}
</script>

现在 PHP 脚本中发生的所有事情就是它使用名为“checkname”的文本框中的名称(使用 POST)查询一个 sql db,然后它回显与该名称相关的段落。通过彻底的测试,我知道 php 脚本可以在没有 AJAX 的情况下工作。

因此,就我现在所拥有的而言,它会从 URL 中的文本框中发送名称,但是它将coddispdiv 留空。

有什么想法吗?

<?php

if( $_SERVER['REQUEST_METHOD'] == 'POST' &&
    isset($_POST['checkname']))
{
$link = mysqli_connect('localhost', 'rhoiydsc_testusr', 'Pass123!', 'rhoiydsc_deathnote');
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "SELECT cod FROM deathnote WHERE victim=?")) {

 /* bind parameters for markers */
 mysqli_stmt_bind_param($stmt, "s",  $_POST['checkname']);

 /* execute query */
 mysqli_stmt_execute($stmt);

/* bind result variables */
mysqli_stmt_bind_result($stmt, $cod);

/* fetch value */
mysqli_stmt_fetch($stmt);

echo $cod;

 /* close statement */
 mysqli_stmt_close($stmt);
}

/* close connection */
mysqli_close($link);

} 



?>

编辑:添加 PHP 代码

4

2 回答 2

0

其实你的代码是正确的。问题是您没有指定要发送的数据:

xmlhttp.open("GET", "check.php", true);

XMLHttpRequest 对象将执行对check.php的 HTTP 请求,仅此而已。如果您想通过 GET 发送数据,只需像这样在 URL 中传递它们:

xmlhttp.open("GET", "check.php?foo=bar&number=1337", true);

如果您执行上述请求,PHP 脚本将在 $_GET 中包含这些数据:

array(
   'foo' => 'bar',
   'number' => '1337', // Note it's still a string, you must cast it as int
)

因此,如果您想从表单中发送名称,请编写以下内容:

xmlhttp.open("GET", "check.php?name=" + escape(name), true);

其中name是包含值的变量。

于 2013-11-15T06:33:01.593 回答
0

试试这个,你在你的checkname()函数中遗漏了一些东西,你的表单需要停止它的默认操作:

<?php
//example check.php
if( $_SERVER['REQUEST_METHOD'] == 'POST' &&
    isset($_POST['checkname']))
{
    echo htmlspecialchars($_POST['checkname']).' was sent as POST and received within PHP and now its been returned.';
    die;
} ?>

<form action="" method="POST" onsubmit="return namecheck(this);">
    Are you in the deathnote? <br/>
    Name: <textarea type="text" name="checkname"></textarea>
    <input type="submit" value="Submit">
</form>
<div id="coddisp"> Nothing yet </div>
<script>
function namecheck(form)
{
    var xmlhttp;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("coddisp").innerHTML=xmlhttp.responseText;
        }
    }
    xmlhttp.open("POST","./check.php",true);
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send("checkname="+escape(form.checkname.value));
    return false;
}
</script>

这里是如何用 jQuery 做同样的事情

<?php
//example check.php, in this we check for bob and return as json
if( $_SERVER['REQUEST_METHOD'] == 'POST' &&
isset($_POST['checkname']))
{
    if($_POST['checkname'] == 'bob'){
        $resp = array('status'=>true,
        'result'=>htmlspecialchars($_POST['checkname']).' found yada.');
    }else{
        $resp = array('status'=>false,
        'result'=>htmlspecialchars($_POST['checkname']).' not found.');
    }

    //set json header
    header('Content-Type: application/json');
    //send respoce
    echo json_encode($resp);

    die;
} ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>

<form action="" method="POST" id="checkname_form">
    Are you in the deathnote? <br/>
    Name: <textarea type="text" name="checkname"></textarea>
    <input type="submit" value="Submit">
</form>
<div id="coddisp"> Type bob above... </div>
<script>
$(function(){
    /* Post form */
    $("#checkname_form").submit(function(event){
        event.preventDefault();
        var request = $.ajax({
            type: "POST",
            url: "./check.php",
            data: $(this).serialize(),
            dataType: "json"
        });
        request.done(function(data) {
            //check on data.status == true
            if(data.status == true){
                $("#coddisp").html(data.result);
            }else{
                //you could do something else here
                $("#coddisp").html(data.result);
            }
        });
        request.fail(function(jqXHR, textStatus, errorThrown) {
            $("#coddisp").html('Error posting form');
        });
    });
});
</script>

</body>
</html>
于 2013-11-15T06:16:28.253 回答