2010-07-20 90 views
1

我对symfony还比较陌生,所以如果这是一个愚蠢的问题,我很抱歉。我使用symfony 1.4和Doctrine。我的同事写了一个JavaScript,使我们的客户端插件报告到我们的服务器:如何在symfony 1.4的actions.class.php中访问POST参数?

$j.post(serverpath, {widget_id:widget_id, user_id:user_id, object_id:object_id, action_type:action_type, text_value:stuff_to_report }); 

我创建了一个routing.yml中路由接收到这个请求:

widget_report: 
    url: /widget/report/ 
    options: {model: ReportClass, type: object } 
    param: {module: widget, action: reports} 
    requirements: 
    object_id: \d+ 
    user_id: \d+ 
    action_type: \d+ 
    sf_method: [post] 

我创建了一个行动的actions.class.php处理请求:

public function executeReports(sfWebRequest $request) { 
    foreach($request->getParameterHolder()->getAll() as $param => $val) { 
     // $param is the query string name, $val is its value 
     $this->logMessage("executeReports: $param is $val"); 
    } 
    try { 
     [...] 
    $actionHistory->setUserId($request->getParameter('user_id', 1)); 
    $this->logMessage("executeReports success: "); 
    } catch { 
     [...] 
    } 
    } 

我的日志文件中报告:

Jul 20 18:51:35 symfony [info] {widgetActions} Call "widgetActions->executeReports()" 
Jul 20 18:51:35 symfony [info] {widgetActions} executeReports: module is widget 
Jul 20 18:51:35 symfony [info] {widgetActions} executeReports: action is reports 
Jul 20 18:51:35 symfony [info] {widgetActions} executeReports success: 

我必须在这里失去一个步骤。在URL中传递变量时(当然,在路由中指定变量),我们有这个工作,但由于各种原因,我们希望使用POST代替。

为什么我的POST参数无法在actions.class.php中访问?

回答

3

试试这个代码:

if ($request->isMethod('post')) { 
    foreach($request->getPostParameters() as $param => $val) { 
     $this->logMessage("executeReports: $param is $val"); 
    } 
} else { 
    $this->logMessage("executeReports: request method is not POST"); 
} 

如果没有帮助,请尝试:

$this->logMessage("executeReports: " . var_export($_POST, true)); 

或启用symfony的调试工具栏,看看是否POST变量从浏览器的到来。

如果$ _POST数组为空,那么问题可能是在错误的请求头,检查,试试这个:

$fp = fopen('php://input','r'); 
$this->logMessage("executeReports: " . stream_get_contents($fp)); 

祝你好运!

编辑:

也许你可以在这里找到$.post not POSTing anything你的答案。

E.g.你应该检查所有的JS变量是否都是空的。

在这两种情况下,我建议您使用Firebug控制台来查看发送到服务器的数据。

+0

谢谢! JavaScript似乎没有发送有效的POST请求。 – Ryan 2010-07-21 02:18:25

+0

Ajax POST请求的正确标题是: xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset = UTF-8'); – Serg 2010-07-21 02:58:55

+0

不知道什么是更好的JavaScript命令? – Ryan 2010-07-21 19:42:14

1

为了响应Sergiy,根据jQuery文档(http://api.jquery.com/jQuery.ajax),任何jQuery ajax请求的默认设置是application/x-www-form-urlencoded和UTF-8。 $ .post仅仅是一个快捷方式,它将ajax'type'设置为'POST'。

它可能是一个案件不匹配,即POST对帖子?

相关问题