php获取curl头_前端之php curl获取接口数据

前端之所以要这样做,也是临时的,就是要拿到数据,但通过API接口地址很多都是跨域的,因为前端写的都是静态页,使用ajax来获取数据的,以Chrome Browser为例

如果没有,下载这个允许跨域扩展,又不想麻烦后台,那就很蛋疼了

27e8cf0bddb0f9db240861edc5b78ecb.png

基本前端都要有服务器环境,不是node 就是 php 或 java 之类的,这里以php为例,讲下curl之转接口,不域跨

首先项目文件夹要在服务器根目前里,也就是通常说的www目录或htdoc目前,这个应该都知道

下面先写一个简单的入门代码,假设直接请求test2.php是跨域的,而test.php是本地服务器的

test.html

Document

var xhr = new XMLHttpRequest();

xhr.open('get', 'test.php', true);

xhr.responseType = 'json';

xhr.send(null);

xhr.onreadystatechange = function() {

if(xhr.status===200 && xhr.readyState===4) {

console.log(xhr.response)

}

}

bd8c51c4f332a04b297d58851a115d5d.png

test.php (使用curl拿test2.php的数据)

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'localhost:8080/test/test2.php');

curl_setopt($curl, CURLOPT_HEADER, 0); // 0:不返回头信息

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 1:内容以变量的形式存储,而不直接输出

$data = curl_exec($curl);

curl_close($curl);

echo $data;

test2.php ( 原数据 )

header('content-type: application/json');

$data = [

'name' => 'tom',

'age' => 24,

'score' => 98,

'class' => '502',

'gender' => 'male'

];

echo json_encode($data);

这样拿到数据,做完后再替换成正确的接口地址。。

进一步,如果有多个请求呢?

那我们就需要一个用于识别的url参数了,这里使用action测试

test.html

Document

function xhr(opts) {

var xhr = new XMLHttpRequest();

xhr.open(opts.type, opts.url, true);

xhr.responseType = opts.dataType;

xhr.send(null);

xhr.onreadystatechange = function() {

if(xhr.status===200 && xhr.readyState===4) {

opts.success(xhr.response);

}

}

}

xhr({

type: 'get',

dataType: 'json',

url: 'test.php?action=grade',

success: function(res) {

console.log(res); // {name: "tom", age: 24, score: 98, class: "502", gender: "male"}

}

});

xhr({

type: 'get',

dataType: 'text',

url: 'test3.php?action=test',

success: function(res) {

console.log(res); // [1,2,3,4,5]

}

});

test.php

function curl($url) {

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);

curl_setopt($curl, CURLOPT_HEADER, 0); // 0:不返回头信息

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 1:内容以变量的形式存储,而不直接输出

$data = curl_exec($curl);

curl_close($curl);

return $data;

}

$action = $_GET['action'];

switch ($action) {

case 'grade':

echo curl('localhost:8080/test/test2.php');

break;

case 'test':

echo curl('localhost:8080/test/test3.php');

break;

}

test3.php

$data = Array(1,2,3,4,5);

echo json_encode($data);

除了curl外,有些情况也可以使用file_get_contents来实现的,有兴趣的可以去了解下。

curl相关参数,请参照:curl手册

吟诗一首:

《九月九日忆山东兄弟》

独在异乡为异客,每逢佳节倍思亲。

遥知兄弟登高处,遍插茱萸少一人。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值