微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用AJAX将变量传递给PHP数组

我查看了与此主题相关的各种其他问题,但我仍在努力寻找我的查询解决方案.

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

我不熟悉通过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”,当添加一个节点时,数字被附加到我表单上任何输入元素的name属性,即header2,header3等.
当我的表单最终提交时,我就可以遍历每个数据字段并将其提交到数据库.

正如我目前所理解的,AJAX数据变量使用密钥对{a:b},其中a =返回键和b =返回值,我希望PHP能够访问该返回值并将其存储到一个可以循环的数组中.结束.
目前成功消息是在我的AJAX调用上触发的,但是我无法访问PHP中的值,而是抛出了“未定义的段定义索引”.

$section = array();
$setSection = $_POST['setSection'];
$section[] = $setSection; 

解决方法:

PHP不会存储您随时间传递的每个setSection变量;每次调用脚本时,都会重置其变量.您可能希望将变量存储在数据库或会话变量中.

这是一种使用session variables方法

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐