简体   繁体   中英

How to pass multiple variables through Ajax?

Below is a ajax code for a comment box which calls php code on another page that inserts comment into comments table. This code works well but it was just a test. Now I want to add userto, userfrom, postid along with comment into comments table For which I will need to pass variables of userto, userfrom etc from index.php to addcomment.php. Can I pass them through this ajax code to addcomments.php?

index.php

<script type="text/javascript">
$(function() {
    $(".comment_button").click(function() {

        var test = $("#content").val();
        var dataString = 'content=' + test;

        if (test == '') {
            alert("Please Enter Some Text");
        } else {
            $("#flash").show();
            $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');

            $.ajax({
                type: "POST",
                url: "addcomment.php",
                data: dataString,
                cache: false,
                success: function(html) {
                    $(".db").after(html);
                    document.getElementById('content').value = '';
                    document.getElementById('content').focus();
                    $("#flash").hide();
                }
            });
        }
        return false;
    });
});
</script>

addcomment.php

if(isset($_POST['content'])) {
  $comment=strip_tags($_POST['content']);
  $com = $db->prepare("INSERT INTO comments (comment) VALUES (:comment)");
  $com->execute(array(':comment'=>$comment)); 
}

您的dataString变量可以是javascript对象:

{ "data1" : "value1", "data2": "value2" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM