【问题标题】:Using AJAX to pass form Submit variable to php page and return output html to DIV使用 AJAX 将表单提交变量传递到 php 页面并将输出 html 返回到 DIV
【发布时间】:2018-01-08 22:52:56
【问题描述】:

我一直在查看大量 AJAX / PHP 文档,并有一个快速的问题请教社区,以帮助我了解基础知识。这是一个简单的表单,用户在其中提交一个值。它被发送到一个 php 计算器,该计算器对该值进行平方并创建一个小的结果回声。

我想了解如何在单击提交后将 php 文件简单地包含到 div“目标”中。而不是传回一个值,我想将 php 文件包含在 div 中。

论坛让我走到了这一步。感谢那些可以查看并提供指导的人。


square.html:

        <!DOCTYPE html>
        <html lang="en">
        
         <head>
        <title> AJAX Insert test</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        </head>
        
        <body> 
        	<form id="calculator" method="post">
          	What Number would you like to square? 
         		<input type="text" name="input_value">
         		<input type="submit" value="Go">
            </form>
        
         <div id="target"></div>
                 
        
    <script>                
    $(function() { 
    $('#calculator').live('submit', function(e) {
            e.preventDefault(); // stops form from submitting naturally
            $.ajax({
                data: $(this).serialize(),
                type: 'POST', //'GET' is default, set to 'POST' if you want.
                url: 'square.php',
                success: function(response) {
                    $("#target").load("square.php");
                }
            });
        });            
    </script>


square.php:

<html>
<p>Results:<br><br></p>
</html>

<?php
$input = htmlspecialchars($_POST['input_value']);
$sum = $input * $input;

echo "You wrote " . $input ." <br>";
echo  $input . " squared = " .$sum . "<br><br>";

?>

【问题讨论】:

    标签: php html ajax forms


    【解决方案1】:

    您会想要显示 square.php 的回声,这意味着您必须执行以下操作:$("#target").load(response);

    【讨论】:

    • 感谢您的回复,但我仍然无法填充
    • 我收到了 $("target").html(response); 的回复!
    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-12
    • 2019-09-29
    相关资源
    最近更新 更多