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

    评论

报告相同问题?