<div class='title' data-x='car'>black</div>
<div class='title' data-x='home'>white</div>
<div class='title' data-x='train'>gold</div>
what is the easyest way to get an associative array on php side:
$arr = ['car' => 'black', 'home' => 'white', 'train' => 'gold'];
Here is the proposal that I have:
Code:
$( document ).ready(function() { var data = {}; $('.title').map(function(){ data[$(this).data('x')] = $(this).html(); }).get(); $.ajax({ type: "POST", url: 'whatever.php', data: data, success: (response)=>{ console.log(response); } }); });
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <div class='title' data-x='car'>black</div> <div class='title' data-x='home'>white</div> <div class='title' data-x='train'>gold</div>
And the file whatever.php
:
$arr = [];
if($_POST) {
foreach ($_POST as $k => $v) {
$arr[$k] = $v;
}
var_dump($arr);
}
Here is the console output:
array(3) {
["car"]=>string(5) "black"
["home"]=>string(5) "white"
["train"]=>string(4) "gold"
}
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.