What I want to do is send an JavaScript Array to a PHP file.
This is what I got:
我想要做的是将JavaScript数组发送到PHP文件。这就是我得到的:
var mydata = [];
console.log(document.getElementsByTagName("input")[0].name);
for (var i = 0; i < document.getElementsByTagName('input').length; i++) {
mydata[document.getElementsByTagName("input")[i].name] = document.getElementsByTagName("input")[i].value;
};
for (var i = 0; i < document.getElementsByTagName('select').length; i++) {
mydata[document.getElementsByTagName("select")[i].name] = document.getElementsByTagName("select")[i].value;
};
console.log(mydata);
$.ajax({
method: "POST",
url: "q.php",
data: {'lol': JSON.stringify(mydata)},
contentType: 'application/json',
dataType: 'json'
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
$('#debug').html(msg);
});
So as you can see, I create an array with a loop, at that moment all is fine. The problem is when I try to sent it through POST with JSON. I don't know if this is the best method...
所以你可以看到,我创建了一个带循环的数组,那时候一切都很好。问题是当我尝试通过POST与JSON发送它。我不知道这是不是最好的方法......
I tried without JSON.stringify();
but the $_POST
still empty
我试过没有JSON.stringify();但是$ _POST仍然是空的
It seems like the post isn't sent, but I can see in the console the XHR post request has been sent.
好像帖子没有发送,但我可以在控制台中看到已发送XHR帖子请求。
1 个解决方案
#1
3
Try to use this code and see the changes.
尝试使用此代码并查看更改。
remove the contentType: 'application/json', dataType: 'json'
删除contentType:'application / json',dataType:'json'
And change var mydata = []
into var mydata = {}
并将var mydata = []更改为var mydata = {}
your ajax should look like this
你的ajax应该是这样的
$.ajax({ method: "POST", url: "q.php", data: {'lol': mydata} }) .done(function( msg ) { alert( "Data Saved: " + msg ); $('#debug').html(msg); });
You dont have to stringify your mydata because you already decleared it as object.
你不必将你的mydata字符串化,因为你已经将它作为对象删除了。
Hope it helps
希望能帮助到你
#1
3
Try to use this code and see the changes.
尝试使用此代码并查看更改。
remove the contentType: 'application/json', dataType: 'json'
删除contentType:'application / json',dataType:'json'
And change var mydata = []
into var mydata = {}
并将var mydata = []更改为var mydata = {}
your ajax should look like this
你的ajax应该是这样的
$.ajax({ method: "POST", url: "q.php", data: {'lol': mydata} }) .done(function( msg ) { alert( "Data Saved: " + msg ); $('#debug').html(msg); });
You dont have to stringify your mydata because you already decleared it as object.
你不必将你的mydata字符串化,因为你已经将它作为对象删除了。
Hope it helps
希望能帮助到你