1

我的 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 >

在 form1 中,我在按钮单击事件上调用了函数,效果很好。但是在按钮上单击它会加载页面并重定向到 ajax_test.php。我们可以说它正确使用ajax吗?

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

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

4

1 回答 1

1

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

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

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

除了这个问题之外,您还没有关闭</head>或打开<body>标签,这本身不是问题,而是一个非常重要的格式问题。另外,请始终type在您的<script>元素上添加一个。最后,你应该关闭<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>
于 2013-07-14T12:15:12.413 回答