简体   繁体   English

如何使用jQuery使用Ajax提交表单,然后获取它提交的页面的输出?

[英]How can I use jQuery to submit a form using Ajax and then get the output of the page it submitted to?

I'm learning PHP and JavaScript, and I'm building a blogging platform. 我正在学习PHP和JavaScript,我正在构建一个博客平台。 I'm working on the comment system. 我正在研究评论系统。 I want to check if the name field matches any users in the database, and if it does, then I want to display a message that the name is taken. 我想检查名称字段是否与数据库中的任何用户匹配,如果匹配,那么我想显示一个消息,提到该名称。

Here's the page that contains the form. 这是包含表单的页面。 (fullpost.php) (fullpost.php)

<!DOCTYPE html>
<html>

<?php
include ('functions.php');
connectDB();

$id = $_GET['id'];

$result = queryDB('SELECT * FROM posts WHERE id='.$id);

$post = mysql_fetch_array($result);
?>

<head>
    <title><?php echo $post['title']; ?> - SimpleBlog</title>
    <link rel="stylesheet" href="style.css" />

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
    <script src="http://ajax.microsoft.com/ajax/jQuery.Validate/1.6/jQuery.Validate.min.js" type="text/javascript"></script>

    <script type="text/javascript">
         $(document).ready(function(){
            $(".commentform").validate();


          });
    </script>

</head>

<body>
<div id="header">
<a href="index.php">SimpleBlog</a>
</div>
<div id="wrapper">
<?php
//post found, display it
if (mysql_num_rows($result) >0) {
        echo '<div class="post">';
        echo '<div class="postheader">';
        echo '<h1>'.$post['title'].'</h1>';
        echo '<h5>by '.$post['author'].' at '.$post['date'].' in '.$post['category'].'</h5>';
        echo '</div>';
        echo '<p>'.$post['fullpost'].'</p>';
        echo '</div>';

    //display comments form
?>
    <div id="commentform">
        <form action="commentsubmit.php" method="POST" class="commentform"/>
            <?php
            //if not logged in, display a name field
            if (!loggedIn()) {
                echo '<label for="author">Name: </label><br />';
                echo '<input type="text" name="author" class="required"/><br />';
            }
            ?>
            <label for="comment">Comment: </label><br />
            <textarea type="text" name="comment" class="required"></textarea><br />
            <input type="hidden" value="<?php echo $id; ?>" name="postid"/>
            <input type="submit" name="submit" Value="Submit" id="sendbutton" class="button"/>
        </form>
    </div>
<?php   
}
else {
    //no posts found
    echo "That post doesn't exist!";
}

$result = queryDB('SELECT * FROM comments WHERE postid='.$id.' ORDER BY date DESC');
$numcomments = mysql_num_rows($result);

//comments found, display them
if (mysql_num_rows($result) >0) {
    if (mysql_num_rows($result) == 1) {
        echo '<h5>'.$numcomments.' Comment:</h5>';
    }
    if (mysql_num_rows($result) > 1) {
        echo '<h5>'.$numcomments.' Comments:</h5>';
    }
    while($comment = mysql_fetch_array($result)) {
        echo '<h6> by '.$comment['author'].' on '.$comment['date'].'</h6>';
        echo '<p>'.$comment['text'].'</p>';
    }       
}
else {
    //no comments found
    echo '<h4>No comments</h4>';
}
?>

</div>
</body>
</html>

Here's the page it submits to. 这是它提交的页面。 (commentnew.php) (commentnew.php)

<?php
//creates a new comment

include('functions.php');

//form submitted
if (isset($_POST['submit'])) {

    //set $author if not logged in
    if(!loggedIn()) {
        //check if username is taken
        connectDB();
        $result = queryDB("SELECT * FROM users WHERE username='".$_POST['author']."'");
        if (mysql_num_rows($result) > 0) {
            die('That name is taken!');
        }
        else {
            //username is not taken
            $author = mysql_real_escape_string($_POST['author']);
        }
    }
    else {
        //user is logged in, set author to their username
        $author = $_SESSION['username'];
    }

    //$author is set, submit
    if (!empty($author)) {
        $postid = mysql_real_escape_string($_POST['postid']);
        $comment = mysql_real_escape_string($_POST['comment']);
        $date = mysql_real_escape_string(date("Y-m-d")." ".date("H:i:s"));

        queryDB('INSERT INTO comments (postid,date,author,text) VALUES ("'.$postid.'","'.$date.'","'.$author.'","'.$comment.'")');
        echo 'Comment Sent!';
    }
}
?>

I tried using $.ajax in the script tags, but it seems to do nothing. 我尝试在脚本标签中使用$ .ajax,但似乎什么也没做。 Can I get an example of how to properly use it? 我可以举一个如何正确使用它的例子吗? How do I get it to pull the message from commentnew.php? 如何让它从commentnew.php中提取消息? Am I going about checking for the username the wrong way? 我要以错误的方式检查用户名吗? Should I be using jQuery's validation plugin somehow? 我应该以某种方式使用jQuery的验证插件吗?

Try this 尝试这个

$("form.commentform").submit(function(e){
   e.preventDefault();

   $.post({
     url: $(this).attr('action'),
     data: $(this).serialize(),
     success: function(reponse){
       //here response will contain whatever you send from the server side page
     }
   });
}):

in general: 一般来说:

var form = $("form.commentform");
$.post(form.attr('action') , form.serialize(), function(data) {
    alert("Response: " + data);
});

Look into jquery ajax function. 查看jquery ajax函数。 That's what I use. 这就是我使用的。 http://api.jquery.com/jQuery.ajax/ http://api.jquery.com/jQuery.ajax/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用Codeigniter,如何通过jquery submit()提交表单? - Using Codeigniter, how can I tell if a form was submitted with jquery submit() 如何获取jQuery Ajax表单提交处理时间,以便我可以禁用使用表单 - how to get jquery ajax form submit process time so i can disable to use the form 使用ajax提交表单,并将提交的值传递到新页面 - Submit form using ajax and pass the value submitted to new page 如何使用Ajax提交表单 - How can I submit form using ajax 如何使用jquery和ajax在第三方url中使用get方法提交表单? - How do i submit a form using get method in third party url using jquery and ajax? 如何使用jquery-ajax提交表单数据? - How do i submit form data using jquery-ajax? 如何使用jQuery在父窗口中提交表单而不刷新父窗口的内容(Ajax提交) - How can I submit a form in a parent window using jQuery without refreshing the contents of the parent window (Ajax submission) 使用jquery / ajax / php提交表单,无需刷新页面。 无法获得电子邮件的表单价值 - submit form with jquery / ajax / php without page refresh. Can't get form value to email 如何接收使用jQuery Submit()提交的表单数据 - how to receive form data submitted with jquery submit() 我可以在使用 jquery ajax 的表单提交上同时调用同一 php 页面上的方法,也可以同时调用另一个 php 代码中的方法吗? - Can i call a method on the same php page also a method in another php code simultaneously on form submit using jquery ajax?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM