简体   繁体   English

尝试将数组从jquery发送到PHP函数

[英]Trying to send an array from jquery to PHP function

I'm trying to load an array in my javascript. 我正在尝试在我的javascript中加载数组。 I need to send this array in some format to a PHP script that I'm going to call. 我需要以某种格式将此数组发送到我要调用的PHP脚本。 In the example below, gSelectedMeds is my array. 在下面的示例中, gSelectedMeds是我的数组。 The value count will tell the PHP script how many meds items to expect to receive. count将告诉PHP脚本期望接收多少个meds项目。 I'm having trouble getting the data from the array into a format that I can send via the data option of $.ajax. 我无法将数组中的数据转换为可以通过$ .ajax的数据选项发送的格式。 Any help would be greatly appreciated!! 任何帮助将不胜感激!!

The part of the code below that is giving me grief at the moment is the data option: 下面的代码部分让我感到悲痛的是数据选项:

$('#export').click(function() {
    $.ajax({
        url:'ajax-exportMeds.php',
        data: 
            {"number":gSelectedMeds.length},
            $.each(gSelectedMeds,
                function(intIndex, objValue){
                    {"med"+intIndex:objValue},
                }
            ),
        type: "GET",
        //dataType: "text",
        success: function(data){
            $('p#allMeds').text('');
            $('a.bank').text('');
            //clear array, bank and storedList divs
            $(this).text('');
            gSelectedMeds[] = '';
            //$('ul#storedList').fadeOut('fast');
            $('ul#storedList').text('');
            return false;
        },
    }),
});

You should send the data as json . 您应该以json的形式发送数据。 Then you can read it using json_decode() in php >= 5.2.0 然后你可以使用php> = 5.2.0中的json_decode()来读取它

I ended up stringing out the array and sending a count at the end of the url that I called: 我最终将数组串起来并在我调用的url末尾发送一个计数:

$('#export').click(function() {
        $.each(gSelectedMeds, 
         function(intIndex, objValue) {
            i=intIndex + 1;
            if(i>1) {string+='&';}
            string+='med'+i+'="'+objValue+'"';
         }
       )

       string += "&count="+i;

        $.ajax({
            url: 'ajax-exportMeds.php?'+string,
            type: "GET",
            dataType: "text",
            success: function(data){
                  $('#dialog_layer').dialog({
                        autoOpen: true,                                                 
                        bgiframe: true,
                        modal: true,
                        closeOnEscape: true,
                        buttons: {
                            "OK": function() { $(this).dialog("close"); }
                        }      
                  })
             }
        })
    });

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

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