Ajax to Curl表单提交

时间:2016-04-21 06:31:29

标签: php ajax curl

我有一个ajax,它将带有文件的表单数据提交给控制器,控制器将使用curl将此表单数据发送到我的api。我怎么能这样做?

我无法直接将表单提交给我的api,它必须通过我的控制器。 :(

我的ajax

data = new FormData();
        data.append( 'file', $( '#file' )[0].files[0] );
        data.append( 'title', title );
        data.append( 'description', description );
        data.append( 'module_id', module_id );
        data.append( 'tags', tags );
        data.append( 'groups', groups );
        $.ajax({
            url: '/controller/upload',
            data: data,
            processData: false,
            contentType: false,
            type: 'POST',
            success: function ( data ) {
                window.location.reload();
            }
        });

我的控制器功能

public function uploadAction(){
    $response = new \Phalcon\Http\Response();
    $response->setContentType('application/json', 'UTF-8');
    $response2 = "{}";
    if($this->request->getPost()){
        $version = $this->session->get("version");
        $data = $this->request->getPost('data');
        $response2 = $this->useCurl("api_link","POST",$data);
    }
    return $response->setContent($response2);
}

1 个答案:

答案 0 :(得分:0)

由于您在url: '/controller/upload'内拨打了url: '/controller/uploadAction',方法,因此uploadAction应为controller

使用cURL:

function useCurl($api_link, $data){
            $ch = curl_init($api_link);
            curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

            $ret = curl_exec($ch);
            curl_close($ch);
            return $ret; 
}
在您的ajax success回调中

success: function ( data ) {
            //do something with data from uploadAction method  (e.g console.log)
          console.log(data);
        }