用guzzle发送表单数据发布请求

时间:2017-12-12 15:31:25

标签: php guzzle

我正在使用guzzle http client,并希望在使用js时实现与此类似的发布请求:

        var formData = JSON.stringify( { id: formID, fields: fields, settings: settings, extra: extra } );
        var data = {
            'action': 'nf_ajax_submit',
            'security': nfFrontEnd.ajaxNonce,
            'formData': formData
        }

        var that = this;

        jQuery.ajax({
            url: nfFrontEnd.adminAjax,
            type: 'POST',
            data: data,
            cache: false,
            success: function( data, textStatus, jqXHR ) {
                try {
                    var response = jQuery.parseJSON( data );
                    nfRadio.channel( 'forms' ).trigger( 'submit:response', response, textStatus, jqXHR, formModel.get( 'id' ) );
                    nfRadio.channel( 'form-' + formModel.get( 'id' ) ).trigger( 'submit:response', response, textStatus, jqXHR );
                    jQuery( document ).trigger( 'nfFormSubmitResponse', { response: response, id: formModel.get( 'id' ) } );
                } catch( e ) {
                    console.log( e );
                    console.log( 'Parse Error' );
                    console.log( e );
                }

            },

如何用guzzle发布帖子请求form-data,我尝试过做同样的事情:

    $url = 'http://ytf.app/wp-admin/admin-ajax.php';
    $data = [];
    $data['security'] = $this->getNonce();
    $data['action'] = 'nf_ajax_submit';
    $data['formData'] = $request->all();
    $formData = json_encode($data);

    $client   = new Client();
    $response = $client->request('POST', $url, [
        'body' =>  $formData,
    ]);

    $body = json_decode($response->getBody(), true);

    if ($body['success'] === true && $body['data'] !== false) {
        return $body['data'];
    }

但是,这不起作用,我该怎么做?

1 个答案:

答案 0 :(得分:0)

$http = new GuzzleHttp\Client;

$response = $http->post('https://your-endpoint.com', [
    'form_params' => [
        'security' =>  $data['security'],
        'action'   =>  $data['action']
    ],
]);