Yii2可以通过json-rpc为前端提供接口数据,通常情况睛会使用异步的形式调用接口,有时也会使用curl调用接口数据。
一、异步调用json-rpc接口
$.ajax({
type: 'POST',
url: "http://localhost/index?r=test",
xhrFields: {withCredentials: true},
data: JSON.stringify([{
jsonrpc: "2.0",
method: "order-list",
params: {id: 3},
id: "1"
}]),
success: function(res){
console.log(res);
},
dataType: "json",
contentType: "application/json-rpc",
error: function(){}
});
分析:json-rpc异步请求接口与普通的ajax异步请求相比,主要在于其设置了请求的content-type,传递的参数中包含了几个字段,jsonrpc method params id,知道了这些,我们通过设置curl的选项与参数,来模拟jsonrpc请求。
二、crul请求josnrpc接口
#请求的url
$url = 'http://localhost/index.php?r=test; //参数是为了防止缓存
#请求参数,如果想一次调用多个接口,data设置成二维数据即可
/*$data1 = [
[
'jsonrpc' => '2.0',
'method' => 'test1',
'id' => 0,
'params' => ['id' => '3']
],
[
'jsonrpc' => '2.0',
'method' => 'test2',
'id' => 0,
'params' => ['id' => '3']
],
];*/
$data = [
'jsonrpc' => '2.0',
'method' => 'test1',
'id' => 0,
'params' => ['id' => '3']
];
#curl初始化
$ch = curl_init();
#请求参数设置
$options = array(
CURLOPT_URL => $url,
CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; rv:12.0) Gecko/20100101 Firefox/12.0",
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPHEADER => Array("Content-Type: application/json-rpc")
);
curl_setopt_array($ch, $options);
#JSON数据
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
#发送请求并接收返回信息
$html=curl_exec($ch);
#获取请求的详细信息 用于调试,可以没有
$info = curl_getinfo($ch); curl_close($ch);
#打印返回数据
var_dump($html);die;