通过POST将JavaScript数组发送到PHP [英] Sending a JavaScript array to PHP via POST

查看:61
本文介绍了通过POST将JavaScript数组发送到PHP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过POST将JavaScript数组发送到PHP文件.

I am trying to send a JavaScript array to a PHP file via POST.

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:

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

当sendData();时引导我前往test.php,我得到:

when sendData(); directs me to test.php I get:

注意:未定义索引:数据

Notice: Undefined index: data

为什么我尝试打印或使用数据变量时没有任何值?

Why doesn't the data variable have any value when I try to print or use it?

推荐答案

1)$ .post('url')-Ajax请求由 $.post()方法,并且您给出了"testing.php" 作为无效的网址.

1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.

2)window.location ='test.php'-用于重定向到特定页面,并且您已重定向到'test.php'而没有任何参数/数据.这就是为什么它显示注意:未定义的索引:数据"

2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"

3)尝试了解ajax的工作原理.跟随它-

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);
}}
?>

这篇关于通过POST将JavaScript数组发送到PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆