php 将 JSON 对象发布到 Symfony 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9522029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 07:00:43  来源:igfitidea点击:

Posting JSON objects to Symfony 2

phpajaxjsonsymfony

提问by greg

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.

我正在使用 Symfony 2 处理一个项目,我构建了一个包来处理我所有的数据库服务,这些服务来回传递 JSON 数据。

My Problem/Question:

我的问题/问题:

  • Is it possible to post a straight up JSON object? Currently I'm spoofing a normal form post for my ajax calls by giving the object a name json={"key":"value"}if I don't give it a name I can't seem to get the data from the Symfony request object $JSON = $request->request->get('json');

  • I want to be able to use the one service bundle to handle both data coming from AJAX calls, or a normal Symfony form. Currently I'm taking the submitted Symfony form, getting the data then using JSON_ENCODE, I just can't work out how to post the data through to my services controller which is expecting request data.

  • 是否可以直接发布 JSON 对象?目前我通过给对象一个名称来欺骗我的 ajax 调用的正常表单帖子,json={"key":"value"}如果我不给它一个名称我似乎无法从 Symfony 请求对象中获取数据$JSON = $request->request->get('json');

  • 我希望能够使用一个服务包来处理来自 AJAX 调用或普通 Symfony 表单的数据。目前我正在提交提交的 Symfony 表单,获取数据然后使用 JSON_ENCODE,我只是不知道如何将数据发布到我的服务控制器,它需要请求数据。

To summarise:

总结一下:

  • I want Symfony to accept a JSON post object rather than a form.

  • I want to pass the JSON object between controllers using Request/Response

  • 我希望 Symfony 接受一个 JSON post 对象而不是一个表单。

  • 我想使用请求/响应在控制器之间传递 JSON 对象

If I'm going about this all wrong, feel free to tell me so!

如果我对这一切都做错了,请随时告诉我!

回答by richsage

If you want to retrieve data in your controller that's been sent as standard JSON in the request body, you can do something similar to the following:

如果您想在请求正文中检索作为标准 JSON 发送的控制器中的数据,您可以执行类似于以下操作:

public function yourAction()
{
    $params = array();
    $content = $this->get("request")->getContent();
    if (!empty($content))
    {
        $params = json_decode($content, true); // 2nd param to get as array
    }
}

Now $paramswill be an array full of your JSON data. Remove the trueparameter value in the json_decode()call to get a stdClassobject.

现在$params将是一个充满 JSON 数据的数组。删除调用中的true参数值json_decode()以获取stdClass对象。

回答by Farid Movsumov

I wrote method to get content as array

我编写了将内容作为数组获取的方法

protected function getContentAsArray(Request $request){
    $content = $request->getContent();

    if(empty($content)){
        throw new BadRequestHttpException("Content is empty");
    }

    if(!Validator::isValidJsonString($content)){
        throw new BadRequestHttpException("Content is not a valid json");
    }

    return new ArrayCollection(json_decode($content, true));
}

And I use this method as shown below

我使用这种方法,如下所示

$content = $this->getContentAsArray($request);
$category = new Category();
$category->setTitle($content->get('title'));
$category->setMetaTitle($content->get('meta_title'));

回答by Ярослав Рахматуллин

javascript on page:

页面上的javascript:

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):

在模板中(在我的例子中是 bestilling.html.twig):

  {% block resources %}
       {{ parent() }}
       <script type="text/javascript">
       jQuery(function(){
           //jQuery('#placeDateWidget').placedate();
           {% autoescape false %}
           {% if products %}

           jQuery('#spreadSheetWidget').spreadsheet({
               enable_listitem_amount: 1,
               products: {{products}}
           });
           jQuery('#spreadSheetWidget').spreadsheet('sumQuantities');
           {% endif %}
           {% endautoescape %}

       });
       </script>
   {% endblock %}

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

Alrite,我想这就是你想要的:)

EDITTo 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()。这是一个与上述精神相同的示例,它不会触发页面刷新。

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'
});