【发布时间】:2017-09-02 16:34:25
【问题描述】:
大家好,我是 symfony 2 的新手,我对使用 ajax 向 symfony 2 中的 php 控制器发送数据感到困惑。我想用谷歌地图创建项目,所以我创建了 MapController:
<?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
我有 javascipt 函数,我试图将 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: {“数据”:null}
【问题讨论】:
标签: javascript php ajax symfony