Get data from php array - AJAX - jQuery

前端 未结 5 985
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 14:10

I have a page as below;





        
相关标签:
5条回答
  • 2020-11-27 14:51

    When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

    You might actually need

    echo json_encode($array);
    

    This should get you what you want.

    EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

    0 讨论(0)
  • 2020-11-27 14:58

    When you echo $array;, the result is Array, result[0] then represents the first character in Array which is A.

    One way to handle this problem would be like this:

    ajax.php

    <?php
    $array = array(1,2,3,4,5,6);
    foreach($array as $a)
        echo $a.",";
    ?>
    

    jquery code

    $(function(){ /* short for $(document).ready(function(){ */
    
        $('#prev').click(function(){
    
            $.ajax({type:    'POST',
                     url:     'ajax.php',
                     data:    'id=testdata',
                     cache:   false,
                     success: function(data){
                         var tmp = data.split(",");
                         $('#content1').html(tmp[0]);
                     }
                    });
        });
    
    });
    
    0 讨论(0)
  • 2020-11-27 15:00

    quite possibly the simplest method ...

    <?php
    $change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
    echo json_encode(change);
    ?>
    

    Then the jquery script ...

    <script>
    $.get("location.php", function(data){
    var duce = jQuery.parseJSON(data);
    var art1 = duce.key1;
    var art2 = duce.key2;
    var art3 = duce.key3;
    });
    </script>
    
    0 讨论(0)
  • 2020-11-27 15:05

    you cannot access array (php array) from js try

    <?php
    $array = array(1,2,3,4,5,6);
    echo json_encode($array);
    ?>
    

    and js

    $(document).ready( function() {
        $('#prev').click(function() {
            $.ajax({
                type: 'POST',
                url: 'ajax.php',
                data: 'id=testdata',
                dataType: 'json',
                cache: false,
                success: function(result) {
                    $('#content1').html(result[0]);
                },
            });
        });
    });
    
    0 讨论(0)
  • 2020-11-27 15:10

    you cannot access array (php array) from js try

    <?php
    $array = array(1,2,3,4,5,6);
    echo implode('~',$array);
    ?>
    

    and js

    $(document).ready( function() {
    $('#prev').click(function() {
      $.ajax({
      type: 'POST',
      url: 'ajax.php',
      data: 'id=testdata',
      cache: false,
      success: function(data) {
        result=data.split('~');
        $('#content1').html(result[0]);
      },
      });
    });
    });
    
    0 讨论(0)
提交回复
热议问题