dongxifu5009
2013-09-29 11:41
浏览 50
已采纳

使用AJAX将数组和字符串从Javascript传递到PHP

I have the following ajax call.

My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123

I want to grab the addList in my PHP file as

$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123

But I couldnt convert the POST string into right forms.

I can create arrays/loops in both sides but it didnt feel right.

Whats the convenient way of doing it?

jQuery.ajax({  
                    type: "post",  
                    url: ajax_var.url,  
                    data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,  
                    success: function(count){  
                        alert("done"); 
                    }  
                }); 

Any help will be appreciated. thanks!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongtan2603 2013-09-29 11:57
    已采纳

    try using followig code.

    you just neeed to locate your form if and url to pass values to :

    var form = new FormData($('#form_id')[0]);
    form.append('view_type','addtemplate');
    $.ajax({
    type: "POST",
    url: "savedata.php",
    data: form,
    cache: false,
    contentType: false,
    processData: false,
    success:  function(data){
    //alert("---"+data);
    alert("Settings has been updated successfully.");
    window.location.reload(true);
    }
    });
    

    this will pass all form element automatically.

    Working and tested code.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongliao6491 2013-09-29 11:50

    When you pass variable with the ajax method from jQuery, you can pass array like this :

    jQuery

        var myArray = newArray();
        myArray.push("data1");
        myString = "data2";
    
    
        jQuery.ajax({  
             type: "post",  
             url: ajax_var.url,  
             data: {array:myArray, param2:myString},
                      ^name     ^value
             success: function(count){  
                 alert("done"); 
             }  
        }); 
    

    PHP

    echo $_POST['array'][0]; // data1
    echo $_POST['param2']; // data2
    
    评论
    解决 无用
    打赏 举报
  • dongwei1895 2013-09-29 11:50

    Change your addList variable to this:

    list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
    

    PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题