【问题标题】:How can I use the data the is return from the Ajax?如何使用从 Ajax 返回的数据?
【发布时间】:2023-07-10 05:52:02
【问题描述】:

我正在使用 ajax 从数据库中检索数据并将其存储为数组,然后返回结果。我的目标是,当用户单击“单击我”按钮时。我想从返回的数据中提醒第一个数组。但是,我下面的代码没有返回任何内容。

<input type="button" id="click_me" value="Click Me"/>

var data_array;

$.post('generate.php', {id: id}, function(data){
                data_array= data;         
});

$('#click_me').click(function(){
   alert(data_array[0]);
});

生成.php

<?php
    header('Content-Type: application/json');
    $array = array('Hello', 'Good Morning', 'Nice to meet you');

    echo json_encode($array);

?>

【问题讨论】:

  • 您在页面加载时发布 -> 不太聪明!使用$(document).ready(function () { /*ajax call*/ });,你必须把你的javascript放在&lt;script&gt;/* js here*/&lt;/script&gt;之间。为什么不点击按钮时发布帖子。请看我的回答。

标签: php jquery arrays


【解决方案1】:

不要将数据数组声明为局部变量,通过删除嵌套成功回调声明中的“var”来使用全局变量:

$.post('generate.php', {id: id}, function(data){
                data_array= data;         
});

【讨论】:

    【解决方案2】:

    由于 ajax 请求是异步的,它不会以这种方式工作。你可以做的一件事是

     var data_array;
    
      $.post('generate.php', {id: id}, function(data){
          data_array= data; 
          $('#click_me').click(function(){
          alert(data_array[0]);
       });        
    });
    

    或者,如果您确保仅在收到数据后单击按钮,您当前的代码将起作用

    第三种选择是在用户单击按钮时检索数据

     $('#click_me').click(function(){
          $.post('generate.php', {id: id}, function(data){
           data_array= data; 
         alert(data_array[0]);        
       });
    
     });
    

    【讨论】:

      【解决方案3】:

      好吧,我看到你想使用 json 和 Javascript。当发送具有 mime 类型 application/json 的 json 时,它会自动传输到数组中。这是因为 json 是一种受人尊敬的数据类型,所有主流浏览器都支持它。

      这是我的 jquery/javascript:

                      $(document).ready(function () { 
                          $('body').on('click', '#clickme', function(){
                              $.post('json.php', function (json){ 
      
                                  // Now do stuff with the json
                                  var table = ''; 
                                  for(q = 0; q < $(json).size(); q++){
                                      table += '<tr><td>' + json[q] + '</td></tr>';
                                  }
                                  var content = '<table>' +table+ '</table>';
                                  $('#put_stuf_inside_me').html(content);
      
                              }); 
                          });
                      });
      

      我的html:

      <input type="button" id="clickme" value="do magic" />
      <div id="put_stuf_inside_me"></div>
      

      我的 php:

      <?php
      
          header('Content-Type: application/json');
          $array = array('Hello', 'Good Morning','Nice to meet you','I put something over here');
      
          echo json_encode($array);
      
      ?>
      

      你知道它是多么容易!

      【讨论】: