在不加载页面的情况下在同一页面中显示ajax内容


Showing ajax content in same page without page load

我的ajax_form.php页面是:

<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script>
function showUser(form, e) {
 e.preventDefault();
 var xmlhttp;
 var submit = form.getElementsByClassName('submit')[0];
 var sent = document.getElementsByName('sent')[0].value || '';
 var id = document.getElementsByName('id')[0].value || '';

if (sent==""){
    document.getElementById("txtHint").innerHTML="";
    return;
}
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(e) {
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.send('sent='+sent+'&id='+id+'&'+submit.name+'='+submit.value);
}
</script>
<form action="ajax_test.php" method="POST">
Enter the sentence: <input type="text" name="sent"><br>
<input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)">
</form>
<br>UPDATE <br>
<form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
<pre>
    Enter the ID : <input type="text" name="id"><br>
    Enter the sentence: <input type="text" name="sent"><br>
</pre>
 <input type="submit" class="submit" value="submit" name="update" >
</form> <br>
<div id="txtHint">
 <b>Person info will be listed here.</b>
 </div>
 </body>
</html>

ajax_test.php为:

<html><head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head> <body > 
<?php
// $q = $_POST["q"];
// you never process the $q var so i commented it
if (isset($_POST['insert']) && $_POST['insert'] !== '') {
echo "Operation: Insert","<br>";
$s = $_POST['sent'];
$flag = 0;
echo "Entered sentence : $s";
if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
    $matches)){ //Values stored in ma. 
    $x = (int) $matches[1][0]; //optionally cast to int
    $y = (int) $matches[1][1];
}
echo "<br>",
     "Positive count :$x",
     "<br>",
     "Negative count :$y",
     "<br>";
//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1 = "INSERT INTO table2 
         (id,sent,pcount,ncount,flag)
         VALUES
         ('','".$_POST['sent']."',' $x ','$y','$flag')";
if (mysqli_query($con, $sql1)) {
   echo "1 record added";
} else {
   die('Error: ' . mysqli_error($con));
}

mysqli_close($con);
}
// -------------------------------UPDATE --------------------------
 if (isset($_POST['update']) && $_POST['update'] !== '') {
echo "Operation: update", "<br>";
 // you say update but you are actually inserting below
$s    = $_POST['sent'];
$flag = 1;
echo "Entered sentence : $s";
if (preg_match_all('/[^=]*=([^;@]*)/', 
    shell_exec("/home/technoworld/Videos/LinSocket/client '$s'"),
    $matches)) //Values stored in ma.
{
    $x = (int) $matches[1][0]; //optionally cast to int
    $y = (int) $matches[1][1];
}
echo "<br>",
     "Positive count :$x",
     "<br>",
     "Negative count :$y",
     "<br>";
//---------------DB stuff --------------------
$con = mysqli_connect('127.0.0.1:3306', 'root', 'root', 'test');
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql1 = "INSERT INTO table2 
         (id,sent,pcount,ncount,flag)
         VALUES
         ('','".$_POST['sent']."',' $x ','$y','$flag')"; // error here again $_POST[id] should be $_POST['id'] with quotes
if (mysqli_query($con, $sql1)) {
  echo "1 record added";
} else { 
  die('Error: ' . mysqli_error($con));
}
 mysqli_close($con);
}
?></html > </body >

在表1中,我把函数调用放在了按钮点击事件上,效果很好。但点击按钮,它加载页面并重定向到ajax_test.php。我们能说它正确使用了ajax吗?

在第二个表单中,我将函数调用保留在表单本身中,并根据脚本中的要求进行编码。但点击按钮就会发生动作。是错误的函数调用还是其他错误?

在这两种情况下,如何在不加载页面(刷新)的情况下显示结果?

问题出在sent参数上——它正在寻找一个名为"send"的输入,但该输入不存在。然后,如果未设置,则退出showUser函数。

以下是有问题的片段(我在下面删除了它):

if (sent==""){
    document.getElementById("txtHint").innerHTML="";
    return;
}

除了这个问题之外,您还没有关闭</head>或打开<body>标记,这本身不是问题,而是一个相当大的格式问题。此外,请始终在<script>元素上放置一个type。最后,您应该以内联方式关闭<meta /><input /><br />元素。一致地格式化你的代码(兄弟元素在它们自己的行上,每个层次有4个空格的选项卡)可以帮助你发现一些小的格式化问题,比如缺少开放体等。

也就是说,这对我有效:

<html>
<head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type" />
    <meta content="utf-8" http-equiv="encoding" />
    <script type="text/javascript">
    function showUser(form, e) {
        e.preventDefault();
        var xmlhttp;
        var submit = form.getElementsByClassName('submit')[0];
        var sent = document.getElementsByName('sent')[0].value || '';
        var id = document.getElementsByName('id')[0].value || '';
        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(e) {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open(form.method, form.action, true);
        xmlhttp.send('sent=' + sent + '&id=' + id + '&' + submit.name + '=' + submit.value);
    }
    </script>
</head>
<body>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <label>Enter the sentence: <input type="text" name="sent"></label><br />
        <input type="submit" class="submit" name="insert" value="submit" onsubmit="showUser(this, event)" />
    </form>
    <h4>UPDATE</h4>
    <form action="ajax_test.php" method="POST" onsubmit="showUser(this, event)">
        <pre>
            <label>Enter the ID:</label>
            <input type="text" name="id"><br>
            <label>Enter the sentence:</label>
            <input type="text" name="sent"><br>
        </pre>
        <input type="submit" class="submit" value="submit" name="update" />
    </form>
    <br />
    <div id="txtHint">
        <b>Person info will be listed here.</b>
    </div>
</body>
</html>