gpt4 book ai didi

javascript - symfony框架中的Ajax调用

转载 作者:行者123 更新时间:2023-12-02 14:38:48 28 4
gpt4 key购买 nike

我想在 symfony2 中进行 ajax 调用。我已经用平面 php 完成了 ajax,但我不知道如何在这个 symfony 框架中进行设置。

    <html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>

<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>

</body>
</html>

我应该把这个请求传递到哪里?到 Controller ??怎么设置路线??有什么方法可以使用平面 php 代替 Controller 吗?

最佳答案

您可以将请求传递给使用路由公开的 Controller 操作: http://symfony.com/doc/current/book/routing.html

然后在你的 html 代码中,如果你使用 twig 并在脚本标签中包含 javascript,你可以这样做

xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");

如果你想访问附加的.js文件中的路由,可以使用FOSJsRoutingBundle生成路由url

关于javascript - symfony框架中的Ajax调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37203194/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com