【问题标题】:Ajax to Curl form submissionAjax 到 Curl 表单提交
【发布时间】:2016-04-21 06:31:28
【问题描述】:

我有一个将表单数据与文件一起提交到控制器的 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);
}

【问题讨论】:

  • $this->useCurl 是做什么的?

标签: php ajax curl


【解决方案1】:

您的url: '/controller/upload' 应该是url: '/controller/uploadAction',,因为您在controller 中调用uploadAction 方法。

使用 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);
        }

【讨论】:

    猜你喜欢
    • 2014-02-14
    • 2017-02-11
    • 2011-06-17
    • 2011-02-05
    • 1970-01-01
    • 2014-02-19
    • 2011-05-09
    • 1970-01-01
    相关资源
    最近更新 更多