weixin_33696106 2015-08-13 09:21 采纳率: 0%
浏览 58

Symfony 2通过Ajax发送JSON

For the purposes of testing I'd like to send parameter of using ajax to Symfony controller but the controller can not read the request.
I Twig I'm trying to send the value of input element via ajax request to Symfony controller. Code in twig:

<body>
<h1>JQuery Ajax Json example</h1>

<script type="text/javascript">
    $(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"/payu",
                type:"POST",
                data:{
                    customerIp:$("#customerIp").val()

                },
                dataType:"JSON",
                success:function(jsonStr){
                    $("#result").text(JSON.stringify(jsonStr));
                }
            });
        });
    });
</script>


<div id="result"></div>
<form name="contact" id="contact" methode="post">
    customerIp:<input  name="customerIp" id="customerIp" value="123.123.123.123"/></br>

    <input type="button" value="submit" name="submit" id="submit"/>
</form>

<h1>{{ result }}Format Data{{ result }}</h1>
</body>

In controller action, I'm reading the request content and decoded it using json_decode function. Code in controller:

 public function payuAction(Request $request)
 {
     $veriable=[];
     if ($content=$request->getContent()) {
         print_r($request);
         $veriable = json_decode(getContent(),true);
         print_r($veriable);
     }

     return $this->render('BartekPsiutekBundle:Default:payu.html.twig', array('result' => $veriable));
}
  • 写回答

7条回答 默认 最新

  • weixin_33701251 2015-08-13 11:09
    关注

    This is because, you send plain text. Your Ajax call requests the answer to be in JSON (with dataType). You cant define the sending format.

    To encode your value use as described here

    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退