postman产生的接口请求ajax请求接口curl请求完整示例

php里面的curl方式

以下方法可以自定义请求的url,请求类型,携带的参数(参数为json类型)
D:\phpStudy\WWW\xxx\app\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use App\Http\Traits\CommonTrait;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class TestController extends Controller
{
    use CommonTrait;
    public function shortUrl(Request $request)
    {
        //测试数据
        request()->offsetSet('url', 'https://blog.csdn.net/sanbingyutuoniao123/article/details/71124655');
        $validator = Validator::make($request->all(), [
            'url' => 'required|url',
        ]);

        if ($validator->fails()) {
            return $this->outPutJson($request->all(), 201, $validator->errors()->first());
        }
        $url = 'https://dwz.cn/admin/create';
        $params = json_encode(['url' => request('url')]);
        $request_type = 'POST';

        //发起curl请求
        $res = $this->makeCurlRequest($url, $request_type, $params);
        //curl请求发生错误,返回错误信息
        if (starts_with($res, 'cURL Error #:')) {
            return $this->outPutJson('', 201, $res);
        }

        $res = json_decode($res);
        $res_code = $res->Code ?? -1;
        if ($res_code == 0) {
            return $this->outPutJson($res->ShortUrl);
        }

        $error_message = [
            '-1' => '短网址生成失败',
            '-2' => '长网址不合法',
            '-3' => '长网址存在安全隐患',
            '-4' => '长网址插入数据库失败',
            '-5' => '长网址在黑名单中,不允许注册',
        ];

        return $this->outPutJson('', 201, $message[$res_code]);
    }
}

D:\phpStudy\WWW\xxx\app\Http\Traits\CommonTrait.php

<?php

namespace App\Http\Traits;

trait CommonTrait
{

    public function outPutJson($data = '', $code = 200, $message = null)
    {
        $message = $message ?? config('response_code')[$code] ?? '';
        return \Response::json(['message' => $message, 'status_code' => $code, 'data' => $data]);
    }

    public function makeCurlRequest($url, $request_type, $params)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $request_type,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_HTTPHEADER => array(
                "Content-Type: application/json; charset=UTF-8",
                "cache-control: no-cache",
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return 'cURL Error #:' . $err;
        } else {
            return $response;
        }

    }

}

如果被curl方获取不到数据,应当是获取数据的方式有问题,因为数据是以流的形式传输过去的.

https://blog.csdn.net/zhezhebie/article/details/92830591

jquery方式:

1.表单传参:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>

<body>
    <div class="response_data">
    </div>
    <script type="text/javascript">
    var form = new FormData();
    form.append("recording", "");
    form.append("uid", "1");
    form.append("itemId", "12");

    var settings = {
        "async": true,
        "crossDomain": true,
        "url": "http://bcclearnning.com/api/order/sendComment",
        "method": "POST",
        "headers": {},
        "processData": false,
        "contentType": false,
        "mimeType": "multipart/form-data",
        "data": form,
        success: function(returndata) {
            alert(returndata);
        },
        error: function(returndata) {
            alert(returndata);
        }
    }

    $('.response_data').text('我要测试一下');
    $.ajax(settings).done(function(response) {
        console.log(response);
    });
    </script>
</body>

</html>

2.普通传参:

    function assignAssistant(channel_user_id) {
    var settings = {
            "async": true,
            "url": "/dataInfo/saveAssistant",
            "method": "POST",
            "headers":  { 'X-CSRF-TOKEN' : '{{ csrf_token() }}' },#防止跨域攻击
            "data": {"channel_user_id":channel_user_id, "assistant_id":$("#assistant option:selected").val()},
            'dataType':"json",
            success: function(returndata) {
                swal('成功!');
            },
            error: function(returndata) {
                swal('失败!');
            }
        }

        $.ajax(settings).done(function(response) {
           window.location.reload();
        });
    }

下面介绍全页面刷新方法:有时候可能会用到

window.location.reload()	#刷新当前页面.
parent.location.reload()	#刷新父亲对象(用于框架)
opener.location.reload()	#刷新父窗口对象(用于单开窗口)
top.location.reload()	#刷新最顶端对象(用于多开窗口)

processData
类型:Boolean
默认值: true。默认情况下,通过data选项传递进来的数据,如果是一个对象(技术上讲只要不是字符串),都会处理转化成一个查询字符串,以配合默认内容类型 “application/x-www-form-urlencoded”。如果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。

发送数据到服务器
默认情况下,Ajax 请求使用 GET 方法。如果要使用 POST 方法,可以设定 type 参数值。这个选项也会影响 data 选项中的内容如何发送到服务器。
data 选项既可以包含一个查询字符串,比如 key1=value1&key2=value2 ,也可以是一个映射,比如 {key1: ‘value1’, key2: ‘value2’} 。如果使用了后者的形式,则数据在发送器会被转换成查询字符串。这个处理过程也可以通过设置 processData 选项为 false 来回避。如果我们希望发送一个 XML 对象给服务器时,这种处理可能并不合适。并且在这种情况下,我们也应当改变 contentType 选项的值,用其他合适的 MIME 类型来取代默认的 application/x-www-form-urlencoded 。

参考:
http://www.w3school.com.cn/jquery/ajax_ajax.asp

jquery发起请求,设置header属性:

$.ajax({
    url: basePath + 'xxx/xxx', #请求路径
    type: 'POST',  #请求类型
    contentType:'application/x-www-form-urlencoded', #传输的参数方式,默认就是这种方式
    data:$('#form_id').serialize(), #传输到后端的数据
    dataType:'json',#期望返回的数据格式是json,默认是'*/*',如果要区分是web请求还是ajax请求,用这个参数判断最好
    success: function(obj) { #接口请求正常的回调,http_code=200
        if (obj.success == true) {
            alert('发送成功')
            ocs_parent_reload(1);
        } else {
            $("#error").html(obj['message']).removeClass('hidden');
            ocs_hide_overlay();
        }
    },
    error: function() { #接口请求正常的回调,http_code!=200,例如服务器错误,返回500
        alert('调用失败,请刷新重试');
        ocs_hide_overlay();
    }
});

补充:

http://www.kkh86.com/it/php-adv/guide-curl-get-post.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值