我希望他们一切都好!我有一个小问题,一切正常,但这不是我想要的功能,
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("https://www.casadelpana.com/api/v1", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
更新JSON数据时,数据会在https://www.casadelpana.com/test进行更新,但会重新加载整个页面。我知道可以使用Ajax来完成,但在返回我感兴趣的变量的地方没有找到类似的东西。如何在不重新加载页面的情况下更新数据?随附完整代码:
<?php
/*
Template Name: Test
*/
?>
<?php header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Formulario</title>
<title>Probando AP.I</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("https://www.casadelpana.com/api/v1", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
</script>
</head>
<body>
<?php
$request = wp_remote_get( 'https://api.casadelpana.com/v1' );
if( is_wp_error( $request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $request );
/* mostrar json original
print_r($body); */
$data = json_decode($body);
/* mostrar json decode en PHP
echo '</br>';
print_r($data);
echo '</br>'; */
$vbs = $data->items['0']->valor; // tomar valor del bolivar respecto al dolar
$vars = $data->items['1']->valor; // tomar valor del peso ARS respecto al dolar
$tasaneta = $vbs / $vars;
$tasacomercial = $tasaneta * 0.85;
echo 'Valor del bolivar: '.$vbs.'';
echo '</br>';
echo 'Valor del Peso ARS: '.$vars.'';
echo '</br>';
echo 'Valor de tasa neta: '.round($tasaneta,0).'';
echo '</br>';
echo 'Valor de tasa comercial: '.round($tasacomercial,0).'';
// Hacer recorrido y obtener todos los valores.
/*
if( ! empty( $data ) ) {
echo '<ul>';
foreach( $data->items as $item ) {
echo '<li>';
echo '<b>' .$item->nombre. '</b>: ' . $item->valor . '</a>';
echo '</li>';
}
echo '</ul>';
}
*/
?>
</body>
</html>
答案 0 :(得分:1)
首先,您的API提供了JSON。
{
"items": [{
"id": "1",
"nombre": "Bolivar",
"valor": "3350"
}, {
"id": "2",
"nombre": "Pesos ARS",
"valor": "41"
}]
}
没有location.reload();你可以这样做。
$.getJSON("https://www.casadelpana.com/api/v1", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
// this will write first item of json to body tag
$("body").text(json.items[0].nombre + " : " + json.items[0].valor);
}
previous = current;
});