jQuery Ajax jSon基于条件循环从数据库设置值

时间:2017-11-02 06:55:38

标签: php jquery json

我有jQuery json从数据库中获取数据。

var list = ["Imsak", "Subuh", "Terbit", "Dhuhur", "Ashar", "Maghrib", "Isya"];

geo = [jsonStr.longitude, jsonStr.latitude, jsonStr.altitude];
timezone = jsonStr.timezone;

prayTimes.tune({ imsak: 2, subuh: 2, terbit: -2, dhuhur: 121, ashar: 2, maghrib: 2, isya: 2 });

var date = new Date(); // today 
prayTimes.setMethod(jsonStr.calculationMethod);
var times = prayTimes.getTimes(date, geo, timezone);

$.ajax(
{
    url: "chk",
    type: "POST",
    data:
    {
    },
    dataType: "JSON",
    success: function (jsonStr)
    {
        var sholatNameLen = jsonStr.sholatName.length;
        for(var i=0; i<sholatNameLen; i++)
        {
            var sholatName = jsonStr.sholatName[i];

            if(jsonStr.time10 == times[list[i].toLowerCase()] + ":00")
            {
                if(list[i] == sholatName)
                {
                    alert(jsonStr.audio_before_adzan);
                }
            }
        }
    }
});

在我的桌子上,我有数据

sholat_name  | audio_before_adzan | iqamah
Subuh        | Alfatihah.mp3      | 10
Dhuhur       | Al-Baqarah.mp3     | 10

在我的PHP jSon上

$time10 = date("H:i:s", strtotime('+ 10 minutes'));
$qAdzanIqomah = mysqli_query($con, "SELECT * FROM tb_sholat WHERE active = 'Y'");
while($dAdzanIqomah = mysqli_fetch_array($qAdzanIqomah))
{
    $sholatName[] = $dAdzanIqomah['sholat_name'];
    $iqamah[] = $dAdzanIqomah['iqamah'];
    $audio_before_adzan[] = $dAdzanIqomah['audio_before_adzan'];
}

$data = array(
    "audio_before_adzan"     => $audio_before_adzan,
    'time10' => $time10
);

echo json_encode($data);

我想要的是,当if(jsonStr.time10 == times[list[i].toLowerCase()] + ":00")为真时,请根据sholatName获取audio_before_adzan。

我尝试了上面的代码,但是这个函数if(list[i] == sholatName)可能不正确。

1 个答案:

答案 0 :(得分:2)

我认为你只是弄乱你的for循环。您似乎对2个不同的循环使用相同的变量i。您应该拆分循环以使其有用:

以下代码只是success - 函数中的部分:

var sholatNameLen = jsonStr.sholatName.length;
    for(var i=0; i<sholatNameLen; i++)
    {
        var sholatName = jsonStr.sholatName[i];
        for (var j = 0; j < list.lenght; j++) {
             if(jsonStr.time10 == times[list[j].toLowerCase()] + ":00")
             {

                if(list[j] == sholatName)
                {
                    alert(jsonStr.audio_before_adzan[i]);
                }
            }
        }
    }