donglanying3855 2012-11-12 16:44
浏览 90
已采纳

使用JSON将Javascript数组传递给PHP

I have 2 selects on my HTML, the options are loaded via my database and the user can switch the options between the boxes, like so:

<select id="column1" multiple size="10" name="FromLB" style="width:150px">
        <?php foreach ($result->result() as $row) { ?>
        <option value="<?php echo $row->id ?>"><?php echo $row->title ?></option>
        <?php } ?>
</select>

example

So far so good, the final plan is for the the user to click Submit and to have access to the data on these two selects in PHP (via an array).

After digging around for a bit, it seems like JSON is the way to go.

I import json.js to my project and get to work:

    function sort_cols(){
            var i=0;
            var p=0;
            var column1 = new Array();
            var column2 = new Array();

            $("#column1 option").each(function()
            {
                column1[i]=$(this).val();
                i=i+1;
            });

            $("#column2 option").each(function()
            {
                column2[p]=$(this).val();
                p=p+1;
            });      

            JSON = JSON.stringify(column1);

            $.ajax({
                url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
                type: 'POST',
                data: JSON,
                success: function(){
                    alert("Success!")
                }


 });
    }

So far I'm only passing one array (for the first select column), but I'm getting an error: Uncaught TypeError: Object ["15","14","1"] has no method 'stringify'

I've been following this answer: How exactly do you use json_decode to pass a javascript array to php?

I'm wondering what am I doing wrong here, and how can I pass my second array (column2) as well?

  • 写回答

3条回答 默认 最新

  • douhan5853 2012-11-12 16:50
    关注

    There's some strange behaviour happening here, most likely caused by the fact your JSON variable is overwriting the browser's native JSON object (or the one provided by json.js in older browsers).

    You can actually pass an object directly to $.ajax, so the following will work:

    $.ajax({
        url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
        type: 'POST',
        data: column1,
        success: function(){
            alert("Success!")
        }
    });
    

    If you want to pass both columns as separate parameters, change it to:

    $.ajax({
        url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
        type: 'POST',
        data: {
            first_column: column1,
            second_column: column2
        },
        success: function(){
            alert("Success!")
        }
    });
    

    They will now be available in your PHP script as $_POST['first_column'] and $_POST['second_column'].

    This way, you leave the heavy lifting of converting your objects to JSON to jQuery, so you don't need to include the json.js library at all.

    Your full code, rewritten:

    function sort_cols(){
        var column1 = [],
            column2 = [];
    
        $("#column1 option").each(function() {
            column1.push($(this).val());
        });
    
        $("#column2 option").each(function() {
            column2.push($(this).val());
        });      
    
        $.ajax({
            url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
            type: 'POST',
            data: {
                first_column: column1,
                second_column: column2
            },
            success: function(){
                alert("Success!")
            }
        });
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划