Symfony 2通过ajax发送json

时间:2015-08-13 09:21:16

标签: php ajax json symfony

出于测试目的,我想将使用ajax的参数发送到Symfony控制器,但控制器无法读取请求。
我Twig我试图通过ajax请求将输入元素的值发送到Symfony控制器。 细枝中的代码:

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

在控制器操作中,我正在读取请求内容并使用json_decode函数对其进行解码。 控制器中的代码:

 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 个答案:

答案 0 :(得分:1)

但是在twig的脚本中,应该有以下

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

            });
        });
    });
</script>

答案 1 :(得分:0)

这是因为您发送纯文本。您的Ajax调用请求答案为JSON(使用dataType)。您无法定义发送格式。

按照here

所述对您的值进行编码

答案 2 :(得分:0)

我认为你应该这样做

$(document).ready(function(){
    $("#submit").click(function(){
        $.ajax({
            url:"/payu",
            type:"POST",
            data:JSON.stringify(values),
            dataType:"JSON",
            success:function(jsonStr){
                $("#result").text(JSON.stringify(jsonStr));
            }
        });
    });
});

并在您的控制器中

$data = json_decode(file_get_contents('php://input'), true);
var_dump($data);

答案 3 :(得分:0)

您尝试访问getContent,之前已将其值放在$content中。奇怪的是,像函数一样调用getContent应该返回错误。调用它的正确方法是$request->getContent()

所以而不是:

json_decode(getContent(),true)

您应该看看是否有效:

json_decode($content,true)

答案 4 :(得分:0)

您应该按名称获取数据,控制器应该看起来像

utf8_unicode_ci

由于您要发送POST请求,因此这是获取数据的方法。 您可以在此处找到文档:http://symfony.com/doc/current/book/http_fundamentals.html

答案 5 :(得分:0)

您的javascript / jquery代码将application/x-www-form-urlencoded类型的数据发送为else。要阅读控制器中的帖子数据,请使用JSON,正如@Pitchwaiz在答案中提到的那样。

您的javascript代码可能如下:

$variable = $request->request->get('customerIp');

你的控制器代码可能是:

$(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"/payu",
                type:"POST",
                data:{
                    customerIp:$("#customerIp").val()

                },
                success:function(data){
                    $("#result").text(data);
                }
            });
        });
    });

控制器在POST数据中检查名为public function payuAction(Request $request) { $veriable=''; if ($request->request->has('customerIp')) { $veriable = $request->request->get('customerIp'); return new Response($veriable); } return $this->render('BartekPsiutekBundle:Default:payu.html.twig', array('result' => $veriable)); } 的变量,如果变量在那里,控制器会将其发回。

答案 6 :(得分:0)

我打算使用ajax在html中捕获参数值,并在controler(symfony)上使用curl在json中发送数据。

<script type="text/javascript">
    $(document).ready(function(){
        $("#submit").click(function(){
            $.ajax({
                url:"send",
                type:"POST",
                crossDomain: true,
                headers: {
                    'Authorization':'Basic MTQ1MjI3OjEzYTk4MGQ0Zjg1MWYzZDlhMWNmYzc5MmZiMWY1ZTUw',
                    'Content-Type':'application/json'
                },
                dataType: 'jsonp',
                data:{
                    customerIp:$("#customerIp").val(),
                    merchantPosId:$("#merchantPosId").val(),
                    description:$("#description").val(),
                    totalAmount:$("#totalAmount").val(),
                    currencyCode:$("#currencyCode").val(),
                    products1name:$("#products1name").val(),
                    products1unitePrice:$("#products1unitePrice").val(),
                    products1quantit:$("#products1quantit").val(),
                    notifyUrl:$("#notifyUrl").val(),
                    continueUrl:$("#continueUrl").val()


                },

                beforeSend:function(){
                    console.log($("#customerIp").val());

                }

            });
        });
    });
</script>
<div id="result"></div>
<form name="contact" id="contact" methode="post">
    customerIp:<input  name="customerIp" id="customerIp" value="123.123.123.123"/></br>
    merchantPosId:<input name="merchantPosId" id="merchantPosId" value="145227"/></br>
    description:<input name="description" id="description" value="Opis zamówienia"/></br>
    totalAmount:<input  name="totalAmount" id="totalAmount" value="1000"/></br>
    currencyCode:<input  name="currencyCode" id="currencyCode" value="PLN"/></br>
    products1name:<input  name="products1name" id="products1name" value="Produkt 1"/></br>
    products1unitePrice:<input  name="products1unitePrice" id="products1unitePrice" value="1000"/></br>
    products1quantit:<input  name="products1quantit" id="products1quantit" value="1"/></br>
    notifyUrl:<input  name="notifyUrl"  id="notifyUrl" value="http://shop.url/notify" /></br>
    continueUrl:<input  name="continueUrl" id="continueUrl" value="http://shop.url/continue" /></br>

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

在symfony的控制器中

public function sendAction(Request $request)
    {
        print('Jestem tutaj');
        $variable = '';
        $merchantPosId='';

        if ($request->request->get('customerIp') != null) {
            $variable = $request->request->get('customerIp');
        }

        if ($request->request->has('merchantPosId')) {
            $merchantPosId = $request->request->get('merchantPosId');
        }
        if ($request->request->has('merchantPosId')) {
            $merchantPosId = $request->request->get('merchantPosId');
        }
        if ($request->request->has('description')) {
            $description = $request->request->get('description');
        }
        if ($request->request->has('totalAmount')) {
            $totalAmount = $request->request->get('totalAmount');
        }
        if ($request->request->has('currencyCode')) {
            $currencyCode = $request->request->get('currencyCode');
        }
        if ($request->request->has('products1name')) {
            $products1name = $request->request->get('products1name');
        }
        if ($request->request->has('products1unitePrice')) {
            $products1unitePrice = $request->request->get('products1unitePrice');
        }
        if ($request->request->has('products1quantit')) {
            $products1quantit = $request->request->get('products1quantit');
        }
        if ($request->request->has('notifyUrl')) {
            $notifyUrl = $request->request->get('notifyUrl');
        }
        if ($request->request->has('continueUrl')) {
            $continueUrl = $request->request->get('continueUrl');
        }
        if (isset($variable)) {
            $data = array(
                "customerIp" => $variable,
                "merchantPosId" => $merchantPosId,
                "merchantPosId" =>$merchantPosId,
            "description=" =>$description,
            "totalAmount=" =>$totalAmount,
            "currencyCode=" =>$currencyCode,
            "products"=>array(
                "name" =>$products1name,
                "unitPrice"=>$products1unitePrice,
                "quantity" =>$products1quantit
            ),
            "notifyUrl=" =>$notifyUrl,
            "continueUrl=" =>$continueUrl

            );
            $data_string = json_encode($data);
            $ch = curl_init('https://secure.payu.com/api/v2_1/orders');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Authorization:Basic MTQ1MjI3OjEzYTk4MGQ0Zjg1MWYzZDlhMWNmYzc5MmZiMWY1ZTUw'
            ));
            $contents = curl_exec($ch);
            curl_close($ch);

        }


        print_r($variable);
        return $this->render('BartekPsiutekBundle:Default:send.html.twig',array('result' => $data_string));
    }