【问题标题】:Showing data after being submitted with ajax用ajax提交后显示数据
【发布时间】:2012-02-10 00:41:51
【问题描述】:

我试图在使用 ajax 提交后显示数据。 ajax 在提交时工作至今,但我必须刷新才能看到它。

这是 jquery:

$('#submit-quote').live("submit", function(){
    var formdata = $(this).serialize();
    $.post("add.php", formdata, function(data) {
        console.log("success"); 
    });
    return false;
});

add.php中的php:

require('includes/connect.php');

$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);

echo $quotes . "Added to database";

mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());

这是我用来获取数据并显示它的 HTML/PHP:

<?php 
    require("includes/connect.php");

    $result = mysql_query("SELECT * FROM entries", $link);
    while($row = mysql_fetch_array($result)){ ?>
        <div class="quote-wrap group">
            <span>Like</span>
            <div class="quote">
                <p>
                <?php echo htmlentities($row['quote']); ?>
                </p>
            </div><!-- /.quote -->
        </div><!-- /.quote-wrap -->

 <?php } ?>

如果需要,以下是表格:

<form id="submit-quote" method="post" >
     <h2> Submit A Quote </h2>
     <textarea name="quote">
     </textarea>
     <input type="submit" name="submit" value="Submit!">
</form>

Ajax在提交的时候有效,但是发送后我也需要显示,怎么办?

【问题讨论】:

  • 你想显示什么,你的成功信息还是提交到数据库的数据?
  • 您知道,live 在 jQuery 1.7.1 中已被弃用。您应该改用onapi.jquery.com/on 旧版本的 jQuery 应该使用 delegate 而不是 live
  • 在我看来,您只需插入 $quote 即可对 SQL 注入持开放态度,除非我错了,而且这不仅仅是字符串插值。小心!
  • 感谢 david 和 john,我只是一个初学者,所以我不太清楚:/ 刚开始接触这些东西。

标签: javascript php jquery ajax


【解决方案1】:

success 回调函数中的 data 变量存储服务器响应。所以要将服务器响应添加到 DOM:

$(document).delegate("'#submit-quote'", "submit", function(){
    $.post("add.php", $(this).serialize(), function(data) {
        $('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + data + '</p></div></div>');
    });
    return false;
});

如果您需要使用事件委托(例如,表单并不总是存在于 DOM 中),那么请使用 .delegate() 而不是 .live(),因为后者在 jQuery 1.7 中已被弃用。

此外,您实际上不需要在变量中缓存$(this).serialize(),因为它只被使用一次(创建变量是不必要的开销)。

由于您的 PHP 代码正在输出 echo $quotes . "Added to database";,服务器响应将是在字符串后附加“已添加到数据库”的引号,这将添加到您的引号列表中。

更新

$(document).delegate("'#submit-quote'", "submit", function(){
    var quoteVal = $(this).find('[name="quote"]').val();
    $.post("add.php", $(this).serialize(), function() {
        $('.inner').append('<div class="quote-wrap group"><span>Like</span><div class="quote"><p>' + quoteVal+ '</p></div></div>');
    });
    return false;
});

请注意,我不再引用服务器响应(实际上我删除了 data 变量)。相反,我将 name="quote" 元素的值保存在提交的表单中,并在 AJAX 请求返回后使用它(这样在添加到 DOM 之前将引用添加到数据库中)。您可以将.append() 代码移到success 回调之外,以便在提交表单时正确运行它(在submit 事件处理程序中)。

更新

如果你想创建一个 DOM 元素来追加而不是编造一个字符串:

$(document).delegate("'#submit-quote'", "submit", function(){
    var quoteVal = $(this).find('[name="quote"]').val();
    $.post("add.php", $(this).serialize(), function() {

        //create parent div and add classes to it
        $('<div />').addClass('quote-wrap group').append(

            //append the "like" span to the parent div
            $('<span />').text('Like');
        ).append(

            //also append the .quote div to the parent div
            $('<div />').addClass('quote').append(

                //then finally append the paragraph tag with the quote text to the .quote div
                $('<p />').text(quoteVal)
            )

        //then after we're done making our DOM elements, we append them all to the .inner element
        ).appendTo('.inner');
    });
    return false;
});

【讨论】:

  • 这只会返回 add.php 中回显的内容,即 echo $quotes 。 “添加到数据库”; .. 我试过 $('.inner').html(data) 但这会从父级中删除所有 html 并插入在 add.php 中回显的内容(.inner 是显示数据的 html 的父级)跨度>
  • 抱歉,我的意思是使用.append() 而不是.html()。前者会将自己添加到.inner 元素的末尾(或者如果您想将其添加到开头使用.prepend().html(&lt;some-html&gt;).empty().append(&lt;some-html&gt;) 相同。我的答案已更新。
  • 我复制并粘贴到您的代码中,但它不起作用。刷新页面,没有提交任何内容
  • @Trippy 在.append() 调用结束时出现错误,对未正确编制的data 变量的引用。再次尝试代码。更重要的是,您应该查看错误控制台以快速发现这些类型的错误(而不是随机发现错误)。
  • 谢谢。它现在“有点”工作。它提交但它提交的地方是空的。刷新页面后显示内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-27
  • 1970-01-01
  • 2015-08-28
相关资源
最近更新 更多