开发者

Trying to send an array from jquery to PHP function

开发者 https://www.devze.com 2022-12-08 04:36 出处:网络
I\'m trying to load an array in my javascript. I need to send th开发者_C百科is array in some format to a PHP script that I\'m going to call. In the example below, gSelectedMeds is my array. The value

I'm trying to load an array in my javascript. I need to send th开发者_C百科is array in some format to a PHP script that I'm going to call. In the example below, gSelectedMeds is my array. The value count will tell the PHP script how many meds items to expect to receive. I'm having trouble getting the data from the array into a format that I can send via the data option of $.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. Then you can read it using json_decode() in php >= 5.2.0


I ended up stringing out the array and sending a count at the end of the url that I called:

$('#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"); }
                        }      
                  })
             }
        })
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消