如何通过Ajax传递多个变量? [英] How to pass multiple variables through Ajax?
问题描述
下面是注释框的Ajax代码,该注释框在另一个页面上调用php代码,该页面将注释插入注释表中.这段代码运行良好,但这只是一个测试.现在,我想将userto,userfrom,postid以及注释添加到注释表中,为此,我需要将index.php中的userto,userfrom等变量传递到addcomment.php.我可以通过此Ajax代码将其传递给addcomments.php吗?
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
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
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对象:
Your dataString
variable can be a javascript object:
{ "data1" : "value1", "data2": "value2" }
这篇关于如何通过Ajax传递多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!