Показать сообщение отдельно
  #398 (permalink)  
Старый 21.02.2018, 17:57
Профессор
Отправить личное сообщение для laimas Посмотреть профиль Найти все сообщения от laimas
 
Регистрация: 14.01.2015
Сообщений: 12,989

Тогда current.json заменить этим

{"current":{"date":"22.2.2018","USD":{"value":56.6 537,"rate":2},"EUR":{"value":69.8087,"rate":1}},"p revious":{"date":"21.2.2018","USD":{"value":56.520 1,"rate":2},"EUR":{"value":69.8928,"rate":1}}}

Код current.php заменить этим

<?
libxml_use_internal_errors();

if($xml = simplexml_load_file('http://www.cbr.ru/scripts/XML_daily.asp?date_req='.date('d/m/Y', strtotime('+1 day')))) {

    $date = strtotime($xml->attributes()->Date);
    
    $currency = json_decode(file_get_contents('current.json'), 1);
        
    if($date > strtotime($currency['current']['date'])) {
        
        foreach ($xml->children() as $child) {
            if($child->NumCode==840 || $child->NumCode==978) $rate[$child->CharCode->__toString()] = (float)str_replace(',', '.', $child->Value);
            if(count($rate)==2) break;
        }
    
        if($rate) {
        
            $currency['previous'] = $currency['current'];
            
            $currency['current']['date'] = date('j.n.Y', $date);
            
            foreach($currency['current'] as $k => &$v) {
                if($k=='date') continue;
                $v['rate'] = ($n = $rate[$k] - $v['value']) < 0 ? 1 : ($n ? 2 : 0);
                $v['value'] = $rate[$k];  
            }
    
            $dir = dirname(__FILE__);
            chdir($dir);
            chmod($dir, 0777);
            
            file_put_contents('current.json',json_encode($currency));
            
            chmod($dir, 0700);
        }
    }
}
?>


HTML/JS

<table>
    <tr>
        <td><span class="previous date"></span></td>
        <td><span class="current date"></span></td>
    </tr>
    <tr>
        <td><span class="previous USD"></span></td>
        <td><span class="current USD"></span></td>
    </tr>
    <tr>
        <td><span class="previous EUR"></span></td>
        <td><span class="current EUR"></span></td>
    </tr>
</table>

<script>
//именно такое и получит Ajax
$.getJSON("http://h116641.s08.test-hf.su/", function(data) {
    $.each(data, function(k, o) {
        $.each(o, function(a, r) {
            $('.'+k+'.'+a).html(
                a=='date' ? r : {'USD':'$','EUR':'€'}[a] + ' ' + r.value.toFixed(2) + ' <b class=' + ['','down','up'][r.rate] +'>' + ['','▼','▲'][r.rate] +'</b>'
            )
        })
    }) 
});
</script>


Стили надо в css описывать, а не забивать ими таблицу. Не надо выдумывать usddata2, usddata3, ... Элемент, в который нужно поместить информацию ему принадлежащую, находится по составному имени класса, которые равны ключам json. Для дат это previous.date, current.date, а для курса соответственно USD или EUR вместо date. И пусть элементов с таким классом будет куча на странице, во все будет помещено.

.attr("title", o.date) удалено, смысла нет, если даты в заголовках указаны.
Ответить с цитированием