我有一个大问题。我用jQuery编写了脚本,它通过摆姿势JSON从Web服务获取数据,并通过响应将Webservice也以JSON格式发回数据。代码如下所示:
function Product(date_from,date_to,API_KEY) {
var self = this;
self.productURI = 'https://api.xxxxxxxxxxxxxxxxxxx/DailySales?FromDate='+date_from+' 00:01 :00&ToDate='+date_to+' 00:01:00';
self.products = new Array();
self.productsDiv = "#products";
self.getAllProducts = function () {
var req = self.pobierz_dane_ajax(self.productURI, "GET");
req.done(function (data) {
self.products = data;
var dataString = JSON.stringify(data);
$.ajax({
type: 'POST',
url: 'write_transactions.php',
data: {
save_transaction: dataString,
date_from: date_from
}
});
});
}
self.pobierz_dane_ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
dataType: 'json',
data: JSON.stringify(data),
crossDomain: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + API_KEY);
}
};
return $.ajax(request);
}
}
我这样调用我的函数:
<script type="text/javascript">
var product = new Product('<?php echo $date_from; ?>','<?php echo $date_to; ?>','<?PHP echo $DE_API; ?>');
product.getAllProducts();
在PHP脚本中,我用PHP解析JSON并将其写入数据库。
当我通过网页(Chrome,Firefox(调用整个过程时,一切正常。当我在 Linux 中的 crontab 中通过以下方式调用它时,问题开始了:
wget -o - 'https...."但它就是不起作用。我需要在后台启动此脚本,所以我需要更好的解决方案....
正确理解您的问题,您目前
- 通过浏览器调用网页
- 网页使用 JS (ajax( 从外部 API 获取数据
- 您解析响应并将其发送到每个 POST 到其他 PHP 脚本(将数据保存到数据库(
现在您使用 wget 从 cron 调用网页,但它不起作用
原因是,wget 只是获取页面并显示 HTML 响应,但不运行 JS 脚本!
你可以使用 phantomjs 代替 wget。它基本上充当无头浏览器,例如可以从cron调用
另一种可能的解决方案是重写一些代码并直接在 php 脚本中执行所有操作
- PHP 脚本从 API 获取数据
- 相同的脚本将数据保存到数据库
- cronjob regulary 使用 wget 调用 PHP 脚本
编辑 - 建议 PHP API 调用的解决方案
<?php
$options = array(
'http' => array(
'method' => 'GET',
'header' => array(
'Authorization: Basic ' . $API_KEY,
'Content-type: application/json'
)
)
);
$context = stream_context_create($options);
$response = file_get_contents($API_URL, false, $context);
//work with response / save to db
Hellll 是的!这太容易:D
我正在为其他人发布我的解决方案:D
$remote_url = 'https://api.xxxxxxxxxxxxxx';
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header' => "Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents($remote_url, false, $context);
print($file);