[英]How to pass variables from jquery fetch function to symfony routes.yaml?
So I want to call a controller in symfony by passing in my route declared in routes.yaml with a jquery fetch function and I want to pass to variables from jquery to the controller. 我怎樣才能做到這一點?
這是我的 jquery。 我稱之為這條路線,我想用它傳遞頂部的兩個變量。
var longitudde = lonLat[0];
var latudde = lonLat[1];
fetch('/weather_request)
.then(function(response) {
return response.json();
}).then(function(json) {
// ...
});
要將這些變量傳遞給 Symfony 中的 routes.yaml:
weather_request:
path: /weather_request
controller: App\Controller\WeatherController::weather
methods: [get]
defaults:
longitude: longitude
latitude: latitude
最后在 WeatherController 中的天氣 function 中傳遞它們:
public function weather($longitude, $latitude)
{
return $this->render('weather/index.html.twig', ['weatherInfos' => $this->weatherService->getWeather($longitude, $latitude)]);
}
那么如何將經度和緯度從 jquery fetch 傳遞到 controller 呢? 我是 Symfony 的新手,所以我可能完全錯了。
我想這可以幫助你:
$.ajax({
url: '{{path('weather_request')}}',
type: 'GET',
data: {
longitude: lonLat[0],
latutide: lonLat[1],
},
success: function(response) {
//called when successful
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
在您的 controller 中:
use Symfony\Component\HttpFoundation\Request;
public function weather(Request $request)
{
if ($request->isXMLHttpRequest()) {
$longitude = $request->query->get('longitude');
$latutide = $request->query->get('latutide');
}
}
對我來說,我是這樣使用它的:在 Js 中:
const obj = {
"longitudde":lonLat[0],
"latudde":lonLat[1]
}
fetch('/weather_request',
{
method:'POST',
headers: {
'Content-Type':'application/json'
},
body:JSON.stringify(obj)
}).then(resp => {
return resp.json();
}).then(res => {
console.log(res)
//...
})
}
在 Controller 路由注釋中,但您可以與 Route.yaml 一起使用:
use Symfony\Component\Routing\Annotation\Route; use Symfony\Component\HttpFoundation\Request; /** * @Route("/weather_request", methods={"POST"}) * */ public function weather(Request $request) { $data = json_decode($request->getContent()); $longitude = $data->longitudde; $latitude = $data->latudde; return $this->render('weather/index.html.twig', [ 'weatherInfos' => $this->weatherService ->getWeather($longitude, $latitude) ]); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.