3

I am using ajax to retrieve data from my database and store it as an array, then I return the result. My goal is, when the users click the "Click Me" button. I want to alert the first array from the data that is returned. However, my code below is not returning anything.

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

generate.php

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

    echo json_encode($array);

?>
4

3 回答 3

1

Don't declare data-array as a local variable, use the global one by removing 'var' in nested success callback declaration:

$.post('generate.php', {id: id}, function(data){
                data_array= data;         
});
于 2013-06-02T19:08:34.847 回答
0

好吧,我看到你想使用 json 和 Javascript。当发送具有 mime 类型的 json 时,application/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);

?>

你看它是多么容易!

于 2013-06-02T20:24:32.807 回答
0

由于 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]);        
   });

 });
于 2013-06-02T19:10:51.307 回答