使用AJAX将变量传递到PHP数组中

3

我看过了与这个主题相关的各种其他问题,但是我仍然在努力寻找解决我的问题的方法。

在我的系统中,我允许管理员向文件附加额外的表单节点,以便他们可以输入任何额外所需的数据,然后将该数据提交到数据库以生成站点主要部分的页面。

我对通过AJAX返回数据的概念还很陌生,所以我可能会误解一些东西,但这是我的代码。

添加节点控制

<div id="nodeControl">
    <div id="addNode">
        <a id="nodeLink" href="#">+</a>
    </div>
</div>

<div id="slideOut">Click to add a new section</div> 

添加节点点击响应函数
var nodeCount = 2;
        $("#nodeLink").click(function(){
            // Local Variables
            var newSection = '<br/><div id="sectionInfo"><div id="sectionWrap"><div id="sectionInner"><label class="inst head">Section ' + nodeCount + '</label><input class="textOver" type="text" name="sectionTitle' + nodeCount + '" value="<?php $title; ?>"> <label class="inst ib">Please enter any text you would like associated with the section.</label> <textarea style="margin-top: 3px" name="sectionContent' + nodeCount + '" value="<?php $body; ?>"></textarea> <label class="inst ib">Please upload the image associated with this section, .PNG reccomended.</label> <input type="file" style="visibility:hidden;" name="img' + nodeCount + '" id="upload" /> <input type="button" id="fileStyle" class="fSOver" value="Upload Pump Image!" /> </div> </div> </div>' ;

            // Append the new section to the document and increment the node count
            $('#sections').append(newSection);
            nodeCount += 1;


            // Call AJAX to pass to PHP
            $.ajax({
                type: "POST",
                url:  "../section.php",
                data: { setSection : newSection },
                success: function() {
                    alert("Success, ajax parsed");
                }
            });

            $(".successDiv").slideDown(150);
            $(".successDiv").delay(1500).slideUp(150);

            return false;
        }); 

在这里,节点计数实例化为“2”,当添加节点时,该数字将附加到表单中任何输入元素的名称属性上,即header2、header3等。这样,在我的表单最终被提交时,我可以循环遍历每个数据字段并将其提交到数据库。
据我目前的理解,AJAX数据变量使用键值对{a:b},其中a=返回的键,b=返回的值。我希望PHP能够访问返回的值并将其存储到一个数组中,以便最后可以通过循环遍历它。当前在我的AJAX调用中触发成功消息,但我无法在PHP中访问值,而是会抛出“sections defined的未定义索引”。
$section = array();
$setSection = $_POST['setSection'];
$section[] = $setSection; 

谢谢Blaze,我会研究一些临时存储机制,如果我将其存储在数据库中,我就不必显式地将返回数据传递给php。 - Halfpint
顺便问一下,我希望你的JavaScript在DOM加载后再运行? - Blazemonger
1个回答

5

PHP不会长时间存储每个传递给它的setSection变量;每次调用脚本时,它的变量都会被重置。您可能需要将变量存储在数据库或会话变量中。

这里有一种使用会话变量的方法:

session_start(); // unless you already started one
if (!isset($_SESSION['section'])) {
    $_SESSION['section'] = array();
}
array_push($_SESSION['section'], $_POST['setSection']);

我已经实现了并理解了它的工作原理,但是 PHP 仍然抱怨“setSection”是未定义的索引。 - Halfpint
那个变量没有像你想的那样被POST到你的脚本中? - Blazemonger
不行,我猜它没有被传回到我的脚本,但成功函数正在触发,所以我不确定我做错了什么。 - Halfpint
如果你将成功回调函数更改为:function(data) { alert("Success: "+data); },你可以显示来自PHP脚本的输出以进一步调试你的代码。 - Blazemonger
在采纳了您的建议后,我重新组织了我的文档,并使其正常工作! - Halfpint
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接