前端之php curl获取接口数据

发布时间:2019-08-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了前端之php curl获取接口数据脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

前端之所以要这样做,也是临时的,就是要拿到数据,但通过API接口地址很多都是跨域的,因为前端写的都是静态页,使用ajax来获取数据的,以Chrome browser为例
如果没有,下载这个允许跨域扩展,又不想麻烦后台,那就很蛋疼了
图片描述

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

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

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
    var xhr = new XMLHttpRequest();
    xhr.open('get', 'test.php', true);
    xhr.responseType = 'json';
    xhr.send(null);
    xhr.onreadystatechange = function() {
        if(xhr.status===200 &amp;& xhr.readyState===4) {
           console.log(xhr.response)
        }
    }
    </script>
</body>
</html>

图片描述
test.php (使用curl拿test2.php的数据)

<?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 ( 原数据 )

<?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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <script>
    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]
        }
    });
    </script>
</body>
</html>

test.php

<?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

<?php
$data = Array(1,2,3,4,5);
echo json_encode($data);

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

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

吟诗一首:

《九月九日忆山东兄弟》

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

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

脚本宝典总结

以上是脚本宝典为你收集整理的前端之php curl获取接口数据全部内容,希望文章能够帮你解决前端之php curl获取接口数据所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。