2017-12-18 135 views
1

我想知道如何让我的ajax请求在crontab中运行? 我在这里有一个ajax请求,从api获取数据,对于每个数据我正在执行ajax post请求来更新我的数据库中的一行。PHP的 - 如何通过在Curl的cron选项卡执行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领域,

我希望有人能帮助我,如果没有可能在阿贾克斯,你能帮帮我在Curl或任何可能的解决方案上完成此操作, 谢谢!

+0

检查我的答案,它的原型一样为你的问题 – Thamaraiselvam

+1

谢谢你,我会去试试吧, – apelidoko

回答

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; 
} 
0

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

+0

你能告诉我演示或为工作示例,我还在困惑,您能不能告诉我一个链接或草稿,谢谢! – apelidoko