最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to pass PHP array values to another file using jQuery Ajax? - Stack Overflow

programmeradmin1浏览0评论

Here is my code,

<?php
$answers = Array( [0] => 13 [1] => 5 [2] => 6 [3] => 11 );
?>

<script>
    function loadData1(val) {
        var dataToSend = {
            'name': val,
            'ans[]': <? php echo $answers; ?>
        };
        $.ajax({
            type: 'POST',
            data: dataToSend,
            url: '<?php echo JURI::ROOT();?>classfiles/sample.php',
            success: function (data) {
                $('#questions').html(data);
            }
        });
    }
</script>

I want the array values in sample.php file, but I don't get any output.

Any useful answers are really appreciated.

Here is my code,

<?php
$answers = Array( [0] => 13 [1] => 5 [2] => 6 [3] => 11 );
?>

<script>
    function loadData1(val) {
        var dataToSend = {
            'name': val,
            'ans[]': <? php echo $answers; ?>
        };
        $.ajax({
            type: 'POST',
            data: dataToSend,
            url: '<?php echo JURI::ROOT();?>classfiles/sample.php',
            success: function (data) {
                $('#questions').html(data);
            }
        });
    }
</script>

I want the array values in sample.php file, but I don't get any output.

Any useful answers are really appreciated.

Share Improve this question edited Mar 26, 2013 at 6:53 Maehler 6,3411 gold badge43 silver badges48 bronze badges asked Jan 24, 2013 at 9:58 BasithBasith 1,0757 silver badges22 bronze badges 2
  • sample.php just contains <?php $answers = Array ( [0] => 13 [1] => 5 [2] => 6 [3] => 11 ); ?> ? – user1157393 Commented Jan 24, 2013 at 10:01
  • 1 have a look at turning your array into a JSON string. – azzy81 Commented Jan 24, 2013 at 10:03
Add a ment  | 

1 Answer 1

Reset to default 7

The line:

var dataToSend = {'name' : val, 'ans[]' : <?php echo $answers; ?> } ;

will print:

var dataToSend = {'name' : val, 'ans[]' : Array } ;

which creates a javascript syntax semantic error (ans = empty string will be posted). Change to:

var dataToSend = {'name' : val, 'ans[]' : <?php echo json_encode($answers); ?> } ;

which prints:

var dataToSend = {'name' : val, 'ans[]' : [13,5,6,11] } ;
发布评论

评论列表(0)

  1. 暂无评论