dsxi70423 2013-12-31 12:39
浏览 44
已采纳

将AJAX查询结果的每个值存储到Javascript变量

Here's a jQuery-ajax function that returns some data from a php file.

$('.up').click(function() {
    var act = $('.active').val();

    $.ajax({
        type: "POST",
        url: "database.php",
        data: {
            value: act
        }
    }).done(function(result) {
        $('#msg').html(result)
    });
});

I get the array result of the query. I have no problem with.

PHP Result :

array(2) {
  [0]=> array(2) { ["Label"]=> string(3) "Group1" ["Count"]=> string(1) "244" }
  [1]=> array(2) { ["Status"]=> string(7) "Group2" ["Count"]=> string(1) "125" }
}

Actual query result is this.

Label   Count
Group1  244
Group2  125

Now that I get the result. I wanted to store the numbers of the Count column to two different javascript variables.

So far I tried with this.

var value1 = "<?php echo htmlentities($data[0]['Count']) ?>";
var value2 = "<?php echo htmlentities($data[1]['Count']) ?>";

Tried replacing with the above piece of code with result in the ajax call.

But when I did this the click event itself was not triggered.

I've saved the numbers to two php variables namely value1 and value2.

And in the result of the ajax call i get the result like 244125.

Help me saving that number to two different javascript variables.

  • 写回答

1条回答 默认 最新

  • doule6314 2013-12-31 14:00
    关注

    I am assuming you are going to do something with this data so you'll need to know what you are looking for.

    Get your PHP to serve up JSON with keys like so:

    {"Bob": "24", "Sue": "12"}
    

    This way you can access the information you need or just loop through the whole lot. I've made a little fiddle which I am hoping will help you understand.

    Ultimately you simply want to use the jQuery $.getJSON to pull the information and then deal with it however you please.

    http://jsfiddle.net/PgVkL/

    If you need PHP to output in the format you specified then you can do:

    $people = array("24", "12", "16", "48");
    var_dump(json_encode($people));
    

    Here's the docs: http://uk3.php.net/json_encode

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加