1、编写输入页面;//demo.html<html><head> <meta charset="utf-8"> <title>获取汇率</title></head><body style="margin-bottom: 10px;"> <P>基本货币:<input type="text" id="basicCoin" name="basicCoin"/>==> <input type="text" id="changeCoin" name="changeCoin"/> <input type="button" id="btn" name="btn" value="提交" onclick="req_server()"/></P> <P id="result"></P> <script> function req_server(){ //获取基本货币 var basicCoin=document.getElementById("basicCoin").value; //获取兑换货币 var changeCoin=document.getElementById("changeCoin").value; var xmlhttp; //创建XMLHttpRequest对象 if (window.XMLHttpRequest){ xmlhttp=new XMLHttpRequest(); }else{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } //设置请求类型,请求地址 xmlhttp.open("GET","deal.php?basicCoin="+basicCoin+"&changeCoin="+changeCoin,true); //发送请求至服务器 xmlhttp.send(); //处理onreadystatechange事件 xmlhttp.onreadystatechange=function() { //结果处理 if (xmlhttp.readyState==4 && xmlhttp.status==200){ var data= eval("("+xmlhttp.responseText+")"); alert(data.status); if(data.status=="ok"){ document.getElementById("result").innerHTML="兑换汇率为:"+data.ret; }else{ document.getElementById("result").innerHTML="处理错误!请检查!"; } } } } </script></body></html>
2、运行效果:
3、php后台处理:<?php //获取参数 $basicCoin = $_GET['basicCoin']; $changeCoin = $_GET['change潮贾篡绐Coin']; $result = json_encode(array("status"=>"err","ret"=>0)); if($basicCoin && $changeCoin){ $str=$basicCoin.$changeCoin; $url="http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={$str}=x"; $file = fopen($url,'r'); $arr=array(); while ($data = fgetcsv($file)) { $arr[] = $data; } fclose($file); if($arr){ //输出汇率 $result = json_encode(array("status"=>"ok","ret"=>$arr[0][1])); exit($result); }else{ exit($result); } } exit($result);?>
4、点击进行测试,效果如下: