我需要从ajax发送到php的字母数字数组中接收键和值的名称。
来自:
<input class="input" name="one" value="1" onchange="myFunction()">
<input class="input" name="two" value="2" onchange="myFunction()">
<input class="input" name="three" value="3" onchange="myFunction()">
从循环中解析
{% for x in y %}
<input class="input" name="{{ x.k }}" value="{{ x.v }}" onchange="myFunction()">
{% endfor %}
我需要print_r()这样的东西:
Array
(
['one'] => 1,
['two'] => 2,
['three'] => 3,
)
如果我这样做:
function myFunction() {
var elementy = document.getElementsByClassName('input');
var data = {};
var key = elementy[0].name;
var value = elementy[0].value;
data = { key: value};
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data} ,
});
}
print_r($ data)return:
Array
(
[key] => 1
)
如果我这样做:
function myFunction() {
var elementy = document.getElementsByClassName('input');
var data = {};
data = {elementy[0].name : elementy[0].value};
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data} ,
});
}
此行Uncaught SyntaxError: Unexpected token [
data = {elementy[0].name : elementy[0].value};
我需要做这样的事情:
function myFunction() {
var data = [];
var elementy = document.getElementsByClassName('input');
for (var i = 0; i < elementy.length; i++){
data[elementy[i].name] = elementy[i].value;
}
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data}
});
}
但没有语法错误Uncaught SyntaxError: Unexpected token [
答案 0 :(得分:1)
如果字段周围有form
元素,最简单的方法是serialize格式:
data: $('form').serialize()
^^^^ if you have more forms, address it by its ID or something similar
如果您没有表格,也可以使用:
data: $('.input').serialize()
因为serialize
也可用于处理各个表单控件的选择。
答案 1 :(得分:0)
而不是
function myFunction() {
var data = [];
var elementy = document.getElementsByClassName('input');
for (var i = 0; i < elementy.length; i++){
data[elementy[i].name] = elementy[i].value;
}
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data}
});
}
应该是
function myFunction() {
var data = {};
var elementy = document.getElementsByClassName('input');
for (var i = 0; i < elementy.length; i++){
data[elementy[i].name] = elementy[i].value;
}
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data}
});
}