好的,我有一个文本字段,可以在其中输入字符串,旁边有一个按钮。
<div class="sidebar-search">
<div class="input-group custom-search-form">
<<label for="riot-summoner-input">Search a Summoner</label><br>
<input type="text" id="riot-summoner-input" class="form-control" placeholder="Type summoner name..." style="margin-bottom: 20px">
<button type="button" id="valid-summoner">Search</button>
</div>
</div>
通过单击此按钮,将执行以下脚本
let res = {{ summoner.summonerLevel }}
$(document).ready(function() {
// Get value on button click and pass it back to controller
$("#valid-summoner").click(function () {
const summoner_input = $("#riot-summoner-input").val();
console.log(summoner_input)
let url = `/coach/?summonerName=${summoner_input}`
history.replaceState(summoner_input, 'Coach Index', url);
console.log(url)
function loadXMLDoc()
{
document.getElementById("display-summonerLevel").innerHTML = `Summoner Level: <h2>${res}</h2>`
}
loadXMLDoc();
});
});
现在据我所知,这将更改我的页面网址以包含插入到文本字段中的值,并将其发送回我的 Controller 而不刷新页面,它确实如此。
现在在我的 Controller 中,我使用该值来执行一些逻辑
/**
* @Route("/", name="app_coach_index", methods={"GET"})
*/
public function index(CoachRepository $coachRepository, riotApi $callRiot, Request $request): ?Response
{
$value = $request->request->get('summoner_input');
if($value != null){
$this->debug_to_console($value . "Hi");
return $this->render('coach/index.html.twig', [
'coaches' => $coachRepository->findAll(), 'summoner'=> $this->showSummoner("$value")
]);}
else{
$this->debug_to_console($value);
return $this->render('coach/index.html.twig', [
'coaches' => $coachRepository->findAll()
]);
}
}
现在有趣的是我正在索引函数中执行此操作。
这是我在索引函数中调用的函数,它实际上是从脚本获取值的函数
/**
* @Route("/?summonerName={summoner_input}", name="show_summoner", methods={"GET"})
*/
public function showSummoner($summoner_input)
{
$call = new ApiClient(ApiClient::REGION_EUW, 'API-KEY-HERE');
return $call->getSummonerApi()->getSummonerBySummonerName($summoner_input)->getResult();
}
现在我看到了这个,我可以看到问题是我在 showSummoner()
函数中获取值,但尝试在索引函数中使用它。这就是为什么当我将其打印到控制台并且变量未定义时我没有得到值。
老实说,我想不出任何逻辑可以解决这个问题。
EDIT!!!!!!!
好的,所以我知道问题出在哪里,问题是当我在索引函数中调用 showSummoner($value) 时。我正在使用 $value = $request->query->get('summoner_input');
我以为我是在索引函数中获取该值,但事实上我是在 showSummoner() 函数中获取它。通过注释就可以看出
对于索引,我在其 url 中没有参数,而在 showSummoner() 中,我在注释中有一个参数。
/**
* @Route("/?summonerName={summoner_input}", name="show_summoner", methods={"GET"})
*/
这确实是事实,因为我在脚本中使用了该 url
let url = `/coach/?summonerName=${summoner_input}`
这样做的原因是我无法在索引网址中使用参数,因为这样我就必须在我使用索引的所有其他地方提供参数,即使我没有参数意味着我没有寻找任何东西。 我希望这能提供更多说明
最佳答案
您正在尝试从 $_GET
全局获取值,而不是 $_POST
。
您可以替换:
$value = $request->request->get('summoner_input');
作者:
$value = $request->query->get('summoner_input');
关于javascript - Symfony Controller 返回的变量始终未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72143677/