【发布时间】:2016-04-06 05:25:37
【问题描述】:
我正在尝试在我的网页中实现货币转换。
这是工作流程
1.用户可以从下拉菜单中选择货币。
2.根据此页面列出的奖品相对于新选择的货币进行了更改。
代码
1.当用户从会话变量中设置的下拉菜单货币值中选择一个项目并使用ajax调用重新加载页面时。
<select id="curr-dropmenu">
<option disabled="" selected="">Choose</option>
<option value="INR">INR</option>
<option value="USD">USD</option>
<option value="AED">AED</option>
<option value="FED">FED</option>
<option value="XBJ">XBJ</option>
</select>
ajax 调用
$('#curr-dropmenu').on('change',function(e){
//ajax call for setting the currency in session
$.ajax({
url:'ajax_set.php',
data:{currency:$(this).val()},
method:"POST",
success:function(data){
location.reload();
},
error:function(data){
alert("ERROR"+JSON.strinfy(data));
}
});
});
在ajax_set.php 文件中
<?php
session_start();
$_SESSION['old_currency']= (!empty($_SESSION['new_currency']))?$_SESSION['new_currency']:'INR';
$_SESSION['new_currency']=$_POST['currency'];
2.当页面重新加载时,从会话中获取以前和当前的货币并向google currency converter发出api请求以将金额转换为所选奖品。
<?php
//getting the currency values from session.
session_start();
//old currency
$from=(!empty($_SESSION['old_currency']))?$_SESSION['old_currency']:'INR';
echo 'From: '.$from.'<br>';
//new currency
$to=(!empty($_SESSION['new_currency']))?$_SESSION['new_currency']:'INR';
echo 'To: '.$to.'<br>';
//amount to be converted.
$prize=array('2000','600','7000','2500','100000');
echo '<br><br>';
for($i=0;$i<5;$i++){
//call the currency convert function
if($from!=$to)
{
$response=currencyConvert($from,$to,$prize[$i]);
$converted_amount=filter_var($response,FILTER_SANITIZE_NUMBER_FLOAT,FILTER_FLAG_ALLOW_FRACTION);
}
else
{
$converted_amount=$prize[$i];
}
echo '<span>'.$converted_amount.' '.$to.'</span><hr/>';
}
//make the api request for convert currency.
function currencyConvert($from,$to,$amount){
// echo '<br>convert'.$f.'to'.$t;
$url = "http://www.google.com/finance/converter?a=$amount&from=$from&to=$to";
$request = curl_init();
$timeOut = 0;
curl_setopt ($request, CURLOPT_URL, $url);
curl_setopt ($request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($request, CURLOPT_USERAGENT,"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($request, CURLOPT_CONNECTTIMEOUT, $timeOut);
$response = curl_exec($request);
curl_close($request);
$regex = '#\<span class=bld\>(.+?)\<\/span\>#s';
preg_match($regex, $response, $converted);
if(!empty($converted))
return ($converted[0])?$converted[0]:0;
}
这只适用于一种方式 例如:如果我将 INR 转换为 USD,则转换是正确的,但是当我选择 USD to INR 时,它会得到错误的输出。
【问题讨论】:
-
我检查了
echo currencyConvert('USD', 'INR', 1.0200);它显示正确的结果,与google.com/finance/converter?a=1.0200&from=USD&to=INR相同