简体   繁体   English

无法正常工作:使用Ajax将POST数据发送到Symfony2控制器

[英]Not working : Send POST Data with Ajax to a Symfony2 Controller

I would like to send Post Data to a Symfony Controller, but it doesn't work. 我想将发布数据发送到Symfony控制器,但是它不起作用。 When I send my data with AJAX, it is sending the POST data, but it is showing red link in the console with no error message or status; 当我使用AJAX发送数据时,它正在发送POST数据,但在控制台中显示红色链接,没有错误消息或状态。 but 200ok in net FF. 但净FF为200ok。 It is sending the request successfully through a normal form. 它以正常形式成功发送了请求。

Here is my Javascript code: 这是我的Javascript代码:

function addprivate() {
    var form_data = $('#private_tuition').serialize();
    var getTeamsUrl = Routing.generate('addprivatetuition', {
        id: form_data
    });
    $.ajax({
        type: "post",
        url: getTeamsUrl,
        data: form_data,
        success: function(response) {
            if (response) {

            } else {

            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            $.notify('Error : Record not found !!', {
                "status": "danger",
                "pos": "top-center"
            });
        }
    });
}

Below is the form tag and js funxtion: 以下是表单标签和js函数:

<form method="post" role="form" id='private_tuition' action="{{base_url}}/privatetutionpdf/" >
    <button type="submit" class='btn btn-primary' onclick='addprivate()' name="btn-save">
        <strong>Generate PDF for client</strong>
    </button>

Here is the PHP Symfony Controller method which received data: 这是接收数据的PHP Symfony Controller方法:

namespace Suntec\Marcus\AssignmentBundle\Controller;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class DefaultController extends Controller
{
....
    /*****************************************************************/
    /**
    * @Route("/addprivatetuition", name="addprivatetuition", options={"expose"=true})
    * @Template()
    */
    public function addprivatetuitionAction(){

        return array();
        //return array();
    }
...

}

looks like you have to prevent the default action of the form, because when you click your submit button the html form will be submitted. 看来您必须阻止表单的默认操作,因为当您单击提交按钮时,将提交html表单。

to only submit via javascript do sth. 只通过javascript做某事。 like: 喜欢:

$('#private_tuition').submit(function(e){ 
   e.preventDefault();    
}

or 要么

$('#private_tuition').submit(function(){ 
    return false;    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM