如何刷新 API DATA Symfony 4



目前,我在Symfony的一个项目中使用API。 我设法在"表"标签中正确显示 API 数据。 但是我想根据带有"选项"的"选择"标签修改"表"列的数据。

你能帮帮我吗,因为我以前从未做过这种事情?

这是我的控制器:

/**
* @Route("/", name="accueil")
**/
public function index(Request $request){
$api = file_get_contents('https://api.coinmarketcap.com/v2/ticker/?convert=EUR&limit=10');
dump($api);
$json = json_decode($api, true);
$id = 1;
return $this->render('pro_crypto/index.html.twig', [
'controller_name' => 'ProCryptoController',
'dataApi' => $json,
'idEvolution' => $id,
]);
}

这是我的树枝:

<table class="table">
<thead>
<tr>
<th scope="col">Nom Crypto</th>
<th scope="col">Symbole</th>
<th scope="col">Rang</th>
<th scope="col">Prix USD</th>
<th scope="col">Capitalisation Boursière USD</th>
<th scope="col">Prix EUR</th>
<th scope="col">Capitalisation Boursière EUR</th>
<th scope="col">
<select id="my_select" onchange="changeId(this.value)">
<option value="1">1H</option>
<option value="2">24H</option>
<option value="3">7J</option>
</select>
</th>
</tr>
</thead>
<tbody>
<tr>
{% for data in dataApi.data %}
<th>{{ data.name }}</th>
<th scope="row">{{ data.symbol }}</th>
<th scope="row">{{ data.rank }}</th>
<td scope="row">{{ data.quotes.USD.price }} $</td>
<td scope="row">{{ data.quotes.USD.market_cap }} $</td>
<td scope="row">{{ data.quotes.EUR.price }} €</td>
<td scope="row">{{ data.quotes.EUR.market_cap }} €</td>
{%if data.quotes.EUR.percent_change_24h < 0 %}
{% if idEvolution == 1 %}
<td scope="row" style="color: red;">{{data.quotes.EUR.percent_change_1h }} %</td>
{% elseif  idEvolution == 2 %}
<td scope="row" style="color: red;">{{data.quotes.EUR.percent_change_24h }} %</td>
{% else %}
<td scope="row" style="color: red;">{{data.quotes.EUR.percent_change_7d }} %</td>
{% endif %}
{% else %}
{% if idEvolution == 1 %}
<td scope="row" style="color: green;">{{data.quotes.EUR.percent_change_1h }} %</td>
{% elseif  idEvolution == 2 %}
<td scope="row" style="color: green;">{{data.quotes.EUR.percent_change_24h }} %</td>
{% else %}
<td scope="row" style="color: green;">{{data.quotes.EUR.percent_change_7d }} %</td>
{% endif %}
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>

我使用 AJAX 在不更新页面的情况下刷新数据。 这是我的 Js:

function changeId(src){
window.location = src;
}
var requestPath = '{{ path('accueil') }}';
$.ajax({
url: requestPath,
type: 'GET',
data: { id: $('#my_select').val() },
success: function (data) {
console.log("xyxy");
},
error: function(){
console.log("ERROR")
}
});

当您将所选选项的值作为名为data的查询参数添加到您的 api 请求时,我假设您正在尝试在控制器中访问此查询参数以更改数据。因此,使用如下所示的示例请求...

GET /api/endpoint?data=7H

。您可以从Request $request对象读取和使用data查询参数,如下所示:

$data = $request->query->get('data');
switch ($data) {
case "7H":
// do something with $json
break;
case "24H":
// do something else with $json
break;
// [..]
default:
// invalid input? throw an exception
}

不,我想更改最后一个"TD"标签中的数据。 我不想更改 API 的设置。我只想根据"选择"标签更改页面上显示的数据。并且页面未刷新 但我不知道怎么做。

最新更新