0

基本上我需要异步插入文本区域的值,但是当我调用函数 insertSQLData() 时,它会显示页面的源代码,除此之外我找不到其他错误。我也省略了数据库代码和任何不相关的代码。

 <?php 
     $q = $_GET["q"];
     $username = $_COOKIE["user"];
 ?>    
  function insertSQLData(str){
    if(str == 0){
        document.getElementById("holder").innerHTML="";
        return;
    }

    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            document.getElementById("holder").innerHTML = xmlhttp.responseText;
        }
    }
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}

<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>

 if(isset($username) && !empty($q)){
    mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
    mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
4

3 回答 3

0

因此,您正在调用 ajax 调用所在的同一页面。显然它会返回代码。

在另一个文件中编写php代码并尝试调用它。有用

于 2012-07-09T09:43:33.360 回答
0

您按照下面给出的条件语句编写代码。

<?php
        if(isset($_GET["q"]))
        {
             $q = $_GET["q"];
             $username = $_COOKIE["user"];


             if(isset($username) && !empty($q)){
                mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
            } elseif(!empty($q)) {
                mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
            }
        }
        else
        {
        ?>
        <script>
         function insertSQLData(str){
            if(str == 0){
                document.getElementById("holder").innerHTML="";
                return;
            }

            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            } else {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    document.getElementById("holder").innerHTML = xmlhttp.responseText;
                }
            }
        xmlhttp.open("GET", "index-async.php?q=+str", true);
        xmlhttp.send();
        }
        </script>
        <form action="" method="get">
    <textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
    <input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
    <div id="holder"></div>
        <?php

        }
?>
于 2012-07-09T09:55:21.533 回答
0

您必须在 php 文件启动之前加载它。
您所要做的就是编写一个控制器,并在任何地方而不是您的 index.php 中使用它,并且(在从 DB 加载这些内容之后)将用户重定向到您的 index.php 页面,提供您需要的那些数据。

于 2012-07-09T04:44:52.577 回答