【问题标题】:PHP - how to execute ajax method via cron tab in Curl?PHP - 如何通过 Curl 中的 cron 选项卡执行 ajax 方法?
【发布时间】:2018-05-31 17:30:37
【问题描述】:

我想知道如何让我的 ajax 请求在 crontab 中运行? 我在这里有一个从 api 获取数据的 ajax 请求,对于我正在执行 ajax 发布请求以更新数据库中的一行的每个数据。

如何在 Curl 中执行此操作?

这是我的脚本,

function getDataFs()
{
    var _token = $("input[name='_token']").val();
    $.ajax({
        url: 'https://url/api/employees', 
        type: 'GET',
        dataType: 'json',
        xhrFields: {
            withCredentials: true
        },
        success: function(response){  
            console.log(response);
            for(i=0; i < response.length; i++)
            {
                $.ajax({
                    url: '/api/update_employees_list',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    type: 'POST',
                    dataType: 'json',
                    data: { 'employee_data': response[i], '_token': _token },
                    success: function(response){
                        console.log(response);
                    }
                })
            }   
        }
    });     
}   

我还传递了请求标头和 xhr 字段,

我希望有人能帮我解决这个问题,如果在 ajax 上不可能,你能帮我在 Curl 或任何可能的解决方案上完成这个, 谢谢!

【问题讨论】:

  • 检查我的答案,它就像你的问题的原型

标签: php ajax curl


【解决方案1】:

您可以执行以下操作并将此文件添加到 Crontab 中。

//getting all initial response
$raw_response = doCurl('https://url/api/employees', false, 'GET');
$response = json_decode($raw_response);

//iterate them
foreach ($response as $value) {
    //set your headers
    $headers = array();
    //set your post data
    $post_arr = array();
    //make your sub requests.
    doCurl($url, $headers, 'POST', $post_arr);
}


function doCurl($url, $headers, $method = 'GET', $post_arr = array()){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_URL, $URL);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);

    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_arr);
    }

    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }

    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

【讨论】:

    【解决方案2】:

    AJAX 是一种仅适用于您的浏览器的技术,但它基于常规 HTTP 请求。使用 Firefox 开发者控制台,您可以简单地将执行的 AJAX 请求复制到 cURL 调用。这可以在你的 cronjob 中使用

    【讨论】:

    • 你能给我看一个演示或工作示例吗,我还是很困惑,你能给我一个链接或草稿吗,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-08-31
    • 2017-07-04
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2012-11-14
    相关资源
    最近更新 更多