简体   繁体   English

jQuery通过ajax post传递数组

[英]jQuery passing an array through ajax post

I'm attempting to pass 4 pieces of data through ajax post (3 text strings, and 1 multidimensional array of text strings).我试图通过 ajax post(3 个文本字符串和 1 个多维文本字符串数组)传递 4 条数据。 When I make my ajax request, I'm only able to retrieve the 3 text strings, not the array.当我发出 ajax 请求时,我只能检索 3 个文本字符串,而不是数组。 This is my function that houses the ajax request...这是我的函数,用于容纳 ajax 请求......

function page_load(page_num, prev_page, next_page, form_arr)
{   
    $.ajax({
        type: 'post',
        cache: false,
        url: 'page_content.php',
        data: {'page_num' : page_num, 
               'prev_page': prev_page, 
               'next_page': next_page, 
               'form_arr' : form_arr
              }
    }).done(function(data){
        $('#main_content').empty().html(data);
    });
}

When the function is executed, all data is (supposed to be) passed to "page_content.php", where I pull the form_arr parameter (with no success)...当函数执行时,所有数据(应该)传递给“page_content.php”,在那里我拉了 form_arr 参数(没有成功)......

<?php

    //test parameter pull
    echo '<pre>';
    var_dump($_POST);
    echo '</pre>';

?>

What I see is this...我看到的是这个...

array(3) {
    ["page_num"]=>
    string(5) "start"
    ["prev_page"]=>
    string(1) "0"
    ["next_page"]=>
    string(1) "1"
}

I've confirmed that the array is being created properly and passed successfully to the "page_load" function (I've been able to loop through the array inside the function, and alert each string).我已经确认数组被正确创建并成功传递给“page_load”函数(我已经能够遍历函数内部的数组,并提醒每个字符串)。 If I change the "form_arr" variable to a string, instead of an array, outside of the function, I am able to pull it, just like the other 3 parameters.如果我将“form_arr”变量更改为字符串,而不是函数外部的数组,则可以像其他 3 个参数一样提取它。

Is there something that I'm missing with this?有什么我想念的吗?


This is my entire js file...这是我的整个js文件...

$(document).ready(function()
{

    //initial page load
    var page_num  = 'start';
    var prev_page = 0;
    var next_page = 1;
    var form_arr = new Array();

    var form_element = new Array();

    form_element['name']  = 'TAG NAME';
    form_element['value'] = 'N/A';

    form_arr.push(form_element);

    page_load(page_num, prev_page, next_page, form_arr);

    //START button click event handler
    $('#main_content').delegate('a.button', 'click', function(e)
    {   
        var btn_id = $(this).attr('href');

        if(!$(this).hasClass('disabled')){
            //call button_click function
            button_click($(this), btn_id);
        }
        e.preventDefault();
    });
    //END button click event handler

    $('#main_content').delegate('form', 'submit', function(e){
        e.preventDefault();
    });

    //START "other" option select from dropdown
    $('#main_content').delegate('select.dropdown', 'change', function(e)
    {   
        var selected = $(this).find("option:selected");
        var target = $(this).children('option.trigger').attr('class').replace('trigger ', '');

        if(selected.hasClass('trigger'))
        {   
            $('.hidden_view.' + target).show();
        }else
        {
            $('.hidden_view.' + target).hide();
        }

    });
    //END "other" option select from dropdown

    /*** FUNCTIONS ***/

    //START button_click function
    function button_click(btn_obj, btn_id)
    {   

        //set next and previous page values
        var page_num = parseInt(btn_id);
        var prev_page = page_num - 1;
        var next_page = page_num + 1;

        /* START LOOP THROUGH FORM AND PULLING VALUES */
        var form = btn_obj.parent();

        var form_arr = form_element_loop(form);

        page_load(page_num, prev_page, next_page, form_arr);
    }
    //END button_click function

    //START page_load function
    function page_load(page_num, prev_page, next_page, form_arr)
    {   

        var ajaxData = JSON.stringify(form_arr);

        $.ajax({
            type: 'post',
            cache: false,
            url: 'page_content.php',
            data: {'page_num' : page_num, 
                   'prev_page': prev_page, 
                   'next_page': next_page, 
                   'form_arr' : ajaxData}
        }).done(function(data){
            $('#main_content').empty().html(data);
        });

    }
    //END page_load function

    //START form_element_loop function
    function form_element_loop(form)
    {   
        var form_arr = new Array();
        var x = 0;

        $(form).children().each(function()
        {   
            var element_tag = $(this).prop('tagName').toLowerCase();

            if(element_tag == 'section' || element_tag == 'article' || element_tag == 'div')
            {
                if($(this).is(':visible'))
                {
                    $(this).children().each(function(){
                        var element_tag = $(this).prop('tagName').toLowerCase();
                        var form_element = form_element_switch($(this));
                    });
                }
            }else
            {
                var form_element = form_element_switch($(this));
            }

            if(form_element.length > 0)
            {
                form_arr[x] = form_element;
            }

                x++;
        });
        return form_arr;
    }
    //END form_element_loop function

    function form_element_switch(form_obj, form_tag)
    {   
        var form_element = new Array();

        switch(form_obj.prop('tagName').toLowerCase())
        {
            case 'a':
                break;

            case 'label':
                break;

            case 'input':
                form_element['name']  = form_obj.attr('name');
                form_element['value'] = form_obj.val();
                break;

            case 'select':
                form_element['name']  = form_obj.attr('name');
                form_element['value'] = form_obj.find(':selected').text();
                break;
            }

        return form_element;
    }

});

You can not send javascript concepts to PHP code. 您无法将javascript概念发送到PHP代码。 In fact, in general, you can only POST strings from client to servers. 实际上,通常,您只能将字符串从客户端发布到服务器。

The smartest way is to encode it in JSON: 最聪明的方法是将其编码为JSON:

function page_load(page_num, prev_page, next_page, form_arr)
{   
    $.ajax({
        type: 'post',
        cache: false,
        url: 'page_content.php',
        data: {'page_num' : page_num, 
               'prev_page': prev_page, 
               'next_page': next_page, 
               'form_arr' : JSON.stringify(form_arr)
              }
    }).done(function(data){
        $('#main_content').empty().html(data);
    });
}

then decode it in PHP into an PHP array@ 然后将其在PHP中解码为PHP数组@

$form_arr = json_decode($_POST['form_arr'],true);

With the limited info you have given, the best I can do is say you cant send an array through ajax. 在您所提供的信息有限的情况下,我能做的最好的事情就是说您无法通过ajax发送数组。 In the past I have solved this issue by calling the JavaScript method join(), which will turn an array into a comma delimited string. 过去,我通过调用JavaScript方法join()解决了此问题,该方法将数组转换为逗号分隔的字符串。 On the back end I would turn that comma delimited string back into an array. 在后端,我将用逗号分隔的字符串转换回数组。 So for example if i wanted to send this array: 因此,例如,如果我想发送此数组:

var arr = ["joe,"sam","jane"];

I would do this in my ajax function: 我将在我的ajax函数中执行此操作:

$.ajax({
    data:{
        arr : arr.join()
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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