如何在JavaScript弹出窗口中显示PHP变量值?

How do I show the PHP variable value in the JavaScript pop-up?

本文关键字:显示 PHP 变量值 窗口 JavaScript      更新时间:2023-09-26

我有以下脚本。用户将传递一个数值,例如123作为URL中的参数,应用程序将从MySQL加载/获取该值,并将其显示在文本区。

。,在URL中输入"example.com/index.php?id=123",将从数据库中取出第123条记录,并将其显示在文本区域中。一切似乎都在工作,但我想显示"源"表的最后一行/id时,提交表单。因此,在弹出窗口中不应该显示"Saved!",而应该显示类似"124"的内容(或者,最后更新的行/号)。

index . php:

<?php
include('connect-db.php');
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
    $id = $_GET['id'];
    $result = mysql_query("SELECT content FROM source WHERE id=$id") or die(mysqli_error()); 
    $row = mysql_fetch_array($result);
       if($row)
    {
     $submit_date = date("Ymd");
     $content = $row['content'];                    
    }
}
?>
<!DOCTYPE html>
    <html>
      <head>
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>        
     <script type="text/javascript"> 
          $(document).ready(function(){
                $("#myform").submit( function () {    
                  $.post(
                   'submit.php',
                    $(this).serialize(),
                    // 
                   // show the last id here!
                   //
                        function(data){ alert("Saved!"); }
                  );
                  return false;   
                });   
            });
    </script>      
      </head>
      <body>
    <div id="header" >
    <form action="submit.php" method="post" id="myform">
    <textarea id="editor" name="editor" id="editor"><?php echo $content; ?></textarea>
    <br/>
    <input type="submit" name="submit" value="Submit" id="submit"/>
    </form>
    </div>
      </body>
    </html>

submit.php:

<?php
include('connect-db.php');
$submit_date = date("Ymd");
$content = mysql_real_escape_string(htmlspecialchars($_POST['editor']));
$ip_address = $_SERVER['REMOTE_ADDR'];
if ($content != '') { 
// 
// Show the variable (last_id) value in the JavaScript above!
//
$last_id = mysql_insert_id();  
mysql_query("INSERT INTO source (submit_date, ip, content) values('$submit_date','$ip_address','$content')") or die(mysql_error());
mysql_close($connection);
}
?>

connect-db:

<?php
 $server = 'localhost';
 $user = 'domdom';
 $pass = 'password@123';
 $db = 'domdom';
 $connection = mysql_connect($server, $user, $pass) or die ("Could not connect to server ... 'n" . mysql_error ());
 mysql_select_db($db) or die ("Could not connect to database ... 'n" . mysql_error ());
?>

请注意,我不需要PDO或MySQLi的任何建议,这在这个时候不重要。但是,任何关于改进安全性/SQL查询等的建议都是受欢迎的。谢谢。

我将试着分两部分回答:

[1] PHP端:在"isset($_GET['id'])"部分,只返回你想要填写的文本区域的内容。例如,在您的数据库中,123 ->"星期五"。只需返回字符串'Friday'。

[2]客户端:不要"提交"表单。调用JS函数,在其中创建XmlHttpRequest,并将请求作为AJAX请求发送到服务器。当您获得返回值时,检查它并填充HTML文本区域。

如果你认为这种方法适合你,你需要更多的细节,请告诉我。我在很多网站上都这样做。