我在php中有一个如何获取api的示例,如何使用jquery做到这一点?我不知道PHP,因此必须从api获取数据。
PHP示例:
$address = 'https://mywebsite.com/api/?gate=clients/getNewsletter/0/json';
$request = array();
$request['authenticate'] = array();
$request['authenticate']['system_key'] = sha1(date('Ymd').'mypass');
$request['authenticate']['system_login'] = "mylogin";
$request['params'] = array();
$request['params']['shops'] = array();
$request['params']['shops'][0] = array();
$request['params']['shops'][0]['shop_id'] = 0;
$request['params']['shops'][0]['approval'] = 'y';
$request['params']['date'] = array();
$request['params']['date']['from'] = '2018-08-10';
$request['params']['date']['to'] = '2018-08-13';
$request['params']['return_elements'] = array();
$request['params']['return_elements'][0] = "1";
$request['params']['results_page'] = 0;
$request['params']['results_limit'] = 100;
$request_json = json_encode($request);
$headers = array(
'Accept: application/json',
'Content-Type: application/json;charset=UTF-8'
);
$curl = curl_init($address);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
curl_setopt($curl, CURLINFO_HEADER_OUT, 1);
curl_setopt($curl, CURLOPT_HEADER, 1);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request_json);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($curl);
$status = curl_getinfo($curl);
curl_close($curl);
这可以在jquery上完成吗?
答案 0 :(得分:1)
您可以使用jQuery ajax函数: https://api.jquery.com/jQuery.ajax/
var d = new Date();
var username = d.getFullYear() + d.getMonth() + d.getDate() + 'mypass';
var parameters = {
'authenticate': {
'system_key': crypto.subtle.digest('SHA-1', new TextEncoder("utf-8").encode(username)),
'system_login': 'mylogin'
},
'params': {
'shops': [{'shop_id': 0, 'approval': 'y'}],
'date': []
}
};
$.ajax({
url: 'https://mywebsite.com/api/?gate=clients/getNewsletter/0/json',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(parameters),
success: function(data) {
// process data
console.log(data);
},
error: function(a, b, c) {
// error handling
console.log(a, b, c);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>