简体   繁体   中英

How to submit an array using HTML and Ajax and send it to PHP as array?

I'm trying to submit some of my HTML inputs as an array, and use it in PHP, but the other inputs are being passed to PHP by Ajax (using jQuery). So I need to get the value of the inputs and send them to a PHP file by Ajax. My inputs are like these:

<input value="..." type="hidden" name="something[]" />
<input value="..." type="hidden" name="something[]" />
<input value="..." type="hidden" name="something[]" />

I have never used this way to submit an array and just saw it. I will be thankful if someone explains this way ( name="something[]" ).

You might want to change your data to JSON format, then in PHP change it back!

JavaScript to JSON: JSON.stringify(array) PHP: json_decode(array)

Assuming you need to POST that payload:

Use the function $.serialize()

var payload = $('[name="somthing[]"]').serialize();
console.log(payload);

$.post( URL, payload);

Or you can use the function .ajax() :

$.ajax({
  method: "POST",
  url: URL,
  data: payload
});

Resource

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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