PHP cURL AJAX 代理问题
怪我咯
怪我咯 2017-04-10 14:40:48
[PHP讨论组]

执行一次时是正常的,短时间(小于一秒)内连续请求多次就会出现只能成功执行一条请求,后面的请求就会报错说未收到回应或者收到多条相同的回应,可执行代码测试。

代码如下:

PHP

<?php
$url = 'http://api.openweathermap.org/data/2.5/weather';

$query = filter_input(INPUT_GET, 'q');
$query || exit;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?q=' . $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = json_decode(curl_exec($ch)) ?: curl_getinfo($ch);
curl_close($ch);

header("Content-Type: application/json", true, 200);
echo json_encode($response);
exit;

HTML

<!doctype html><html><head><title>Get Weather</title><style>table{border-collapse:collapse;}td,th {border:1px solid #ccc; padding: 3px 5px;}</style></head><body><table><thead><tr><th>name</th><th>id</th><th>main</th><th>description</th><th>icon</th></tr></thead><tbody></tbody></table><script src="http://cdn.staticfile.org/jquery/2.1.0/jquery.js"></script><script>
(function($) {
    var cities = ['Shanghai,CN', 'Chongqing,CN', 'Wuhan,CN', 'Guangzhou,CN', 'Shanghai,CN'];
    $.each(cities, function(_, city) {
        getWeather(city);
    });

    function getWeather(city) {
        $.getJSON('./ajax_proxy.php?q=' + city, function(resp) {
            var table = $('table');
            $.each(resp.weather, function(_, o) {
                var tr = $('<tr>');
                tr.append($('<td>').html(resp.name));
                $.each(o, function(k, v) {
                    tr.append($('<td>').html(v));
                });
                tr.appendTo(table.find('tbody'))
            });
        });
    }
})(window.jQuery);
</script><body></html>
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
大家讲道理

我觉得应该是API这边做了限制,请看OpenWeatherMap API官网上写的:

How to work with us effectively

These are several recommendations how to work with our free service in more effective way:

  • Do not send requests more then 1 time per 10 minutes from one device.The weather is changing not so frequently as usual.
  • Use the name of the server as api.openweathermap.org. Please never use the IP of the server.
  • If possible please use city ID or city name instead of city coordinates. It is let us use cash server more effective.
  • The service is absolutely free and has some limitation of capacity. So if you do not get respond from server please do not try to repeat your request immediately, please repeat it in 10 min. Also please store your previous request data.
  • If you need secured SLA please contact us.

以及价目表上的情况,明确表明API有频率限制了。而且是申请了API的情况下。像你这样直接就抓接口的人肯定有很多,也就是共用一个接口的人很多,所以更甚。所以正确的做法是去老老实实的申请一个Key啦,然后按照倒数第二条写的一样,按照规定频率去做查询然后存储数据,自己网站这边访问只需要读取存储好的数据就好啦。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号