duanpiyao2734 2016-09-15 17:14
浏览 29

Javascript在AJAX响应中声明一个全局变量

After sending an Ajax post request, I get an array as a response. I want to use this array in another function, I tried to declare the variable before setting its value without putting it in any function.

var their_Info = [];
    $.ajax({
            url: "My PHP url",
            type: "post",
            data: {username:usernames} ,
            success: function (response) {
               their_Info = JSON.parse(response);
            });

If I want to use their_Info in a separate function I am getting undefined..

Below is the php script for reference:

<?php
header('Access-Control-Allow-Origin: *');
$usernames = $_POST['username']; 
//$ids = join("','",$usernames); 
$link = mysqli_connect("localhost", "root", "vKukRKWZRE", "table");
$acc_Info = array();
foreach ($usernames as $value) {
    $query = "SELECT * FROM users WHERE username = '$value'";
    $show = mysqli_query($link, $query) or die("Error");
    while ($row = mysqli_fetch_array($show)) {
        array_push($acc_Info, explode(',', $row['wear']));
    }
}
echo json_encode($acc_Info);
?>
  • 写回答

2条回答 默认 最新

  • dqs66973 2016-09-15 17:20
    关注

    If you try to use their_Info before the AJAX completes, it will obviously return undefined because AJAX is async.

    The possible solution

    Call your function inside success with the data as an argument. By this, you will be using the response only after the AJAX completes

    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题