Posting JSON objects to Symfony 2

后端 未结 3 896
广开言路
广开言路 2020-11-27 05:35

I\'m working on a project using Symfony 2, I\'ve built a bundle to handle all my database services which passes JSON data back and forward.

My Problem/Question:

3条回答
  •  被撕碎了的回忆
    2020-11-27 05:51

    javascript on page:

    function submitPostForm(url, data) {
        var form                = document.createElement("form");
            form.action         = url;
            form.method         = 'POST';
            form.style.display  = 'none';
    
        //if (typeof data === 'object') {}
    
        for (var attr in data) {
            var param       = document.createElement("input");
                param.name  = attr;
                param.value = data[attr];
                param.type  = 'hidden';
            form.appendChild(param);
        }
    
        document.body.appendChild(form);
        form.submit();
    }
    

    after some event (like a click on "submit"):

    // products is now filled with a json array
    var products = jQuery('#spreadSheetWidget').spreadsheet('getProducts');
    var postData = {
    'action':   action,
    'products': products
    }
    submitPostForm(jQuery('#submitURLcreateorder').val(), postData);
    

    in the controller:

       /**
        * @Route("/varelager/bestilling", name="_varelager_bestilling")
        * @Template()
        */
       public function bestillingAction(Request $request) {
           $products   = $request->request->get('products', null); // json-string
           $action     = $request->request->get('action', null);
    
           return $this->render(
               'VarelagerBundle:Varelager:bestilling.html.twig',
               array(
                   'postAction' => $action,
                   'products' => $products
               )
           );
       }
    

    in the template (bestilling.html.twig in my case):

      {% block resources %}
           {{ parent() }}
           
       {% endblock %}
    

    Alrite, I think that's what you wanted :)

    EDIT To send something without simulating a form you can use jQuery.ajax(). Here is an example in the same spirit as above which will not trigger a page refresh.

    jQuery.ajax({
        url:        jQuery('#submitURLsaveorder').val(),
        data:       postData,
        success:    function(returnedData, textStatus, jqXHR ){
            jQuery('#spreadSheetWidget').spreadsheet('clear');
            window.alert("Bestillingen ble lagret");
            // consume returnedData here
    
        },
        error:      jQuery.varelager.ajaxError, // a method
        dataType:   'text',
        type:       'POST'
    });
    

提交回复
热议问题