简体   繁体   English

通过POST将JavaScript数组发送到PHP

[英]Sending a JavaScript array to PHP via POST

I am trying to send a JavaScript array to a PHP file via POST. 我试图通过POST将JavaScript数组发送到PHP文件。

JS: JS:

var songlist = ['song1', 'song2', 'song3'];

var sendData = function(){
    var data = songList.join(',')
    $.post('test.php', {data: data}).always(function() {
        window.location = 'test.php';
    });
}
sendData();

test.php: test.php的:

<?php
$songData = $_POST['data'];
$songData = explode(',', $songData); 
print_r(array_values($songData));
?>

when sendData(); 当sendData(); directs me to test.php I get: 指导我test.php我得到:

Notice: Undefined index: data 注意:未定义的索引:数据

Why doesn't the data variable have any value when I try to print or use it? 当我尝试打印或使用它时,为什么数据变量没有任何值?

That's not how POST request works. 这不是POST请求的工作原理。 Read more about Ajax, but for now, that's how you should do it. 阅读有关Ajax的更多信息,但就目前而言,您应该如何做到这一点。

 var songlist = ['song1', 'song2', 'song3']; var sendData = function() { $.post('test.php', { data: songlist }, function(response) { console.log(response); }); } sendData(); 
 // test.php <?php $songData = $_POST['data']; print_r($songData); ?> 

1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid. 1)$ .post('url') - Ajax请求是通过$.post()方法完成的,你已经将"testing.php"作为url给出了无效的。

2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. 2)window.location ='test.php' - 这用于重定向到特定页面,您已经重定向到'test.php'而没有任何参数/数据。 Thats why its showing "Notice: Undefined index: data" 这就是为什么它显示“通知:未定义的索引:数据”

3) Try to understand how ajax works. 3)尝试了解ajax的工作原理。 Follow it - 跟着它 -

var songlist = ['song1', 'song2', 'song3'];

var sendData = function() {
  $.post('test.php', {
    data: songlist
  }, function(response) {
    console.log(response);
  });
}
sendData();
// test.php
<?php
if(isset($_POST)){
    if(isset($_POST['data'])){
    $songData = $_POST['data'];
    print_r($songData);
}}
?>
var songlist = ['song1', 'song2', 'song3'];
var sendData = function(){
var data = songList.join(',')
$.post('testing.php', {data:     data}).always(function() {
window.location = "test.php?data=$data";
});
}
sendData();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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