要向访问您网站的访问者隐藏API密钥,请在您自己的网站上使用PHP脚本充当中继。它接收Ajax请求(没有API密钥);添加您的密钥并发出自己的API请求;然后将响应返回到浏览器。
例如Javascript
var dataString = "item=" + $('#item').val() + "&qty=" + $('#quantity').val(); $.ajax({type: "POST", url:"/myrelays/getstockdata.php", data: dataString, success: function(data){ your function to handle returned data } });getstockdata.php脚本(一个非常粗糙的框架):
<?phpheader('Content-Type: application/json; charset=utf-8');$api_key = 'xyz1234';$result = array('status'=>'Error','msg'=>'Invalid parameters');// your pre to sanitize and assign (Ajax) post variables to your PHP variables// if invalid: exit(json_enpre($result));// make API request with $api_key$url = 'https://api.provider.com/stockdata.json?key=' . $api_key . '&item=' . $item . '&qty=' . $qty;$ch = curl_init($url); curl_setopt($ch,CURLOPT_FAILONERROR, TRUE); // identify as error if http status pre >= 400curl_setopt($ch, CURLOPT_HEADER, 0);curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); // returns as string$api_response = curl_exec($ch);if(curl_errno($ch) || curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200 ) : $result['msg'] = 'Item not found or unable to get data. ' . curl_error($ch); curl_close($ch); exit(json_enpre($result));endif;curl_close($ch);$depredData = json_depre($api_response, true);// check for success and do any server side manipulation of $depredData$result['status'] = 'OK'];$result['msg'] = '$depredData';exit(json_enpre($result));?>注意:在脚本中,我通常将“ HTML”传递回浏览器。因此,脚本的“ Json”位可能需要更改,例如,可能不需要“ header”(脚本的第一行)。



