简体   繁体   English

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

[英]Pass Array and String from Javascript to PHP with AJAX

I have the following ajax call. 我有以下ajax电话。

My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123 我的addList变量包含一个字符串:list = Sports&list = Cars&list = Outdoor&new_list = 123123

I want to grab the addList in my PHP file as 我想在我的PHP文件中获取addList作为

$_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. 但是我无法将POST字符串转换为正确的形式。

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! 谢谢!

try using followig code. 尝试使用followig代码。

you just neeed to locate your form if and url to pass values to : 您只需要查找表单if和url即可将值传递给:

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. 工作和经过测试的代码。

When you pass variable with the ajax method from jQuery, you can pass array like this : 当您使用jQuery中的ajax方法传递变量时,您可以像这样传递数组:

jQuery 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 PHP

echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2

Change your addList variable to this: 将您的addList变量更改为此:

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] PHP会将名为list[]的项目解析为一个数组,您会发现以下值: $_POST['list'][0]$_POST['list'][1]$_POST['list'][2]

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

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