开发者

Passing arrays to php page

I've been struggling on how to solve this. I wasn't able to find a开发者_开发问答ny solutions over the internet.

This a part of the code:

var params = "nome=" + encodeURI(document.getElementById("nome").value )+
"&email=" + encodeURI(document.getElementById("email").value )+
"&telefone=" + encodeURI(document.getElementById("telefone").value )+
"&produto=" + encodeURI(document.getElementsByName("produto[]") )+
"&quantidade=" + encodeURI(document.getElementsByName("quantidade[]") )+
"&msg=" + encodeURI(document.getElementById("msg").value );
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close"); 

"produto" and "quantidade" are arrays, coming from a form. How to pass this values to my php page (I want to send the content via email).


using jquery the serialize() function will turn your array into a string to pass to your server

$('[name=produto]').serialize()

http://api.jquery.com/serialize/


I briefly remember if you do this: (this is also how jQuery serialize works)

var myArrayToPost = [1, 2, 3];
var postString = "";
for(<-- Iterate over myArrayToPost -->) {
   postString += "MyArray[]=" + value + "&";
}
<-- Post postString -->

Basically you want the post to be this:

"MyArray[]=FirstValue&MyArray[]=SecondValue&MyArray[]=ThirdValue"

Then PHP will automatically put that into an array in $_POST so you can get it:

$_POST['MyArray'] // which will equal 
                  // array(
                  //   'FirstValue',
                  //   'SecondValue', 
                  //   'ThirdValue'
                  // );


When you pass parameters in http request, each one of them is a pair name=value, so produto=1 is a parameter produto with 1 as its value. To take an "array" from http request you must build the several parameters with same name, something like produto=1&produto=2& ...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜