php 如何使用 Symfony 和 Jquery 发出 POST Ajax 请求
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19375349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a POST Ajax request with Symfony and Jquery
提问by Xavier
I need to store some map parameter in my symfony project, to do this i need to implement some Ajax in my view which will be able to pass some info to the controller.
我需要在我的 symfony 项目中存储一些地图参数,为此我需要在我的视图中实现一些 Ajax,它能够将一些信息传递给控制器。
I read the docs, try to write some code but i can't make it works. And Ajax is really painfull to debug. Here is the controller part :
我阅读了文档,尝试编写一些代码,但我无法使其正常工作。而且 Ajax 调试起来真的很痛苦。这是控制器部分:
/**
* @Route("/ajax", name="_recherche_ajax")
*/
public function ajaxAction()
{
$isAjax = $this->get('Request')->isXMLHttpRequest();
if ($isAjax) {
return new Response('This is ajax response');
}
return new Response('This is not ajax!', 400);
}
And the JS :
和 JS :
map.on('zoomend', function(e) {
// use callback e variable
console.log('zoom: ' + e.target.getZoom());
$.ajax({
type: "POST",
url: "/recherche/ajax",
data: {
zoom: e.target.getZoom()
},
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
I check the url recherche/ajax
it does exist and return the 'This is not Ajax' as expected. But the console.log does not return any value...
我检查recherche/ajax
它确实存在的 url并按预期返回“这不是 Ajax”。但是 console.log 没有返回任何值...
Is that the right way to do this ?
这是正确的方法吗?
EDIT :It looks like the controller can't handle POST Request. I tried to modify the annotations to :
编辑:看起来控制器无法处理 POST 请求。我试图将注释修改为:
/**
* @Route("/ajax", name="_recherche_ajax")
* @Method({"GET", "POST"})
*/
But it returns :
但它返回:
([Semantical Error] The annotation "@Method" in method MySite\SiteBundle\Controller\RechercheController::ajaxAction() was never imported. Did you maybe forget to add a "use" statement for this annotation?)
回答by sf_tristanb
Try this,
尝试这个,
/**
* @Route("/ajax", name="_recherche_ajax")
*/
public function ajaxAction(Request $request)
{
if ($request->isXMLHttpRequest()) {
return new JsonResponse(array('data' => 'this is a json response'));
}
return new Response('This is not ajax!', 400);
}
In case of you sending an Ajax request, you need to return json/plaintext/xml
data, and not a whole Response
object.
如果您发送 Ajax 请求,您需要返回json/plaintext/xml
数据,而不是整个Response
对象。
PS:Do not forget to add use statment for Request
and JsonResponse
PS:不要忘记为Request
and添加 use 语句JsonResponse
EDIT :As the error message you added says, you need to import the annotation @Method
by using :
编辑:正如您添加的错误消息所说,您需要@Method
使用以下方法导入注释:
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
回答by B?a?ej Krzakala
I was looking the entire internet and didn't find any solution to similar problem. But i found it-> I had neither issue with the controller, nor the javascript/jquery/ajax nor the security issues. It was in .... wait for it.... in HTML. i had to add type="button" into html tag, otherwise whole page was refreshing. 4 hours wasted on debugging purposes.. but lessons learned.
我正在查看整个互联网,但没有找到类似问题的任何解决方案。但我找到了它-> 我既没有控制器问题,也没有 javascript/jquery/ajax 问题,也没有安全问题。它在......等待它......在HTML中。我不得不将 type="button" 添加到 html 标签中,否则整个页面都令人耳目一新。在调试目的上浪费了 4 个小时……但吸取了教训。
How to debug problems? 1. Check if ajax is sending post and matching post route on the client side. Firefox -> f12 -> network -> watch the POST events 2. Check the symfony profiler (very usefull tool!) on the -> /app_dev.php/ (dev enviroment) -> Get Request/Response submenu end take last 10, if You see the POST route check closely if its return code and parameters (you wont see response, if its set other than HTML response) 3. In your controller do some action that can be checked if the script inside this route was executed. If so, and You see no response its either on the server side (controller) or client side (twig/ajax/html) 4. Code examples:
如何调试问题?1.检查ajax是否在客户端发送post和匹配的post路由。Firefox -> f12 -> 网络 -> 观察 POST 事件 2. 检查 symfony 分析器(非常有用的工具!) -> /app_dev.php/(开发环境)-> 获取请求/响应子菜单结束最后 10,如果你看到 POST 路由,仔细检查它的返回代码和参数(你不会看到响应,如果它设置的不是 HTML 响应) 3. 在你的控制器中做一些可以检查是否执行了此路由中的脚本的操作。如果是这样,并且您在服务器端(控制器)或客户端(twig/ajax/html)上都看不到响应 4. 代码示例:
Button in html (this was my issue)
html 中的按钮(这是我的问题)
<button name="button" id="button" class="button" type="button" value="100"> Click me </button>
Ajax in html or other included js file:
html 或其他包含的 js 文件中的 Ajax:
function aButtonPressed(){
$.post('{{path('app_tags_sendresponse')}}',
{data1: 'mydata1', data2:'mydata2'},
function(response){
if(response.code === 200 && response.success){
alert('success!');
}
else{
alert('something broken');
}
}, "json");
}
Now.. server side. Controller:
现在..服务器端。控制器:
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class JsonApiController extends Controller
/**
* @Route("/api/programmers")
* @Method("POST")
*/
public function sendResponse()
{
if(isset($_POST['data1'])){
$json = json_encode(array('data' => $_POST['data1']), JSON_UNESCAPED_UNICODE);
file_put_contents("test.json", $json);
return new JsonResponse($json);
}
return new Response('didn't set the data1 var.');
}
}
File put contents
create new file in web directory. If it was matched and file is created that means, that You matched the route, but didn't get the response
File put contents
在 web 目录中创建新文件。如果匹配并创建了文件,则意味着您匹配了路由,但没有得到响应