2
嗨,大家好我是symfony 2中的新成员,我对symfony 2中的php控制器发送ajax数据感到困惑。我想用google map创建项目,所以我创建MapController:在symfony2中发送Ajax数据到php控制器
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
class MapController extends Controller
{
/**
* @Route("/", name="homepage")
*/
public function indexAction(Request $request)
{
// replace this example code with whatever you need
return $this->render('map/map.html.twig', [
'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
'contData' => ['lat' => '51.24591334500776', 'lng'=> '22.56967306137085']
]);
}
public function saveAction(Request $request)
{
$data = $request->request->get('params');
return new JsonResponse(['data' => $data], Response::HTTP_OK);
}
}
然后创建路由:
app:
resource: '@AppBundle/Controller/'
type: annotation
map:
path: /map
defaults: { _controller: AppBundle:Map:index }
requirements:
page: '\d+'
map_save:
path: /map/save
defaults: { _controller: AppBundle:Map:save }
methods: [POST]
所以,当我去到路线:
我显示我的模板map.html.twig
有我有SCRIPT关闭在那里我试图ajax的数据发送到控制器的一些:
marker.addListener("click", function() {
//!
var http = new XMLHttpRequest();
var url = "map/save";
var params = marker.position.lat();
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
但是我在这个响应NULL: {“data”:null}
我知道,但这个函数的名字只是现在测试。所以当我在我的MapController中创建一个saveCoordinatesAction方法时,应该如何在javascript中查看我的var url?我试图用“map/saveCoordinatesAction”,“map/saveCoordinates”,“app_dev.php/map/saveCoordinatesAction”等组合,但是这个请求stil没有达到,没有来到我的php函数在这个控制器中。 – johnyT
mam POST http ://localhost/googlemap/web/app_dev.php/saveCoordinatesAction 404(Not Found),szczerze jestem nowy w symfony kilka godzin temupostawiłemprojekt,żebysięnauczyći te rutingi mnie jesczetrochęmylą,wcześniejużywałemnp Yii2 framework,gdzie w ogole nie trzebasięmartwićo takei sprawy – johnyT
如果你的基地址是'http:// localhost/googlemap/web/app_dev.php /',那么你应该使用所有的这个(包括'http://'协议前缀)在你的javascript调用的URL中,例如'http:// localhost/googlemap/web/app_dev.php/saveCoordinates'('app_dev.php'是可选的,把它留在你的生产服务器上),但是你需要在'routing.yml'文件中为这个地址定义一个路由,就像你为'map' URL所做的一样。 – Najki