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;
