请帮我找出这个php代码的javaScript/jQuery等价物。
<?php
$from = 'USD';
$to = 'INR';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = @fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
echo 'Value of $1 in Indian Rupees is Rs. '.$dollarValue;
试试这个。。。
您可以使用jquery-ajax将值传递到php页面,并从ajax成功中获得输出。
$.ajax({
type: "POST",
url: "ajax.php",
data: {from:from,to:to},
success: function(data){
alert(data);
//you can get output form ajax.php, what you expected.
}
});
ajax.php
<?php
$from = $_POST['from'];
$to = $_POST['to'];
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$handle = @fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
echo 'Value of $1 in Indian Rupees is Rs. '.$dollarValue;
参考编号:http://api.jquery.com/jquery.ajax/
在这种情况下,fopen的等价物就像执行jQuery Ajax GET请求,但是由于finance.yahoo.com位于不同的域上,并且他们的服务器不允许跨域请求,因此GET请求会出错。为了解决这个问题,您需要将PHP脚本放在同一个域上,并对此进行请求。
在服务器上保存脚本
parse.php
<?php
$response =array('result'=>'failed','message'=>'missing params');
if(isset($_GET['from']) && isset($_GET['to'])){
$from = $_GET['from'];
$to = $_GET['to'];
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from .'&X='. $to;
$handle = @fopen($url, 'r');
if ($handle) {
$result = fgets($handle, 4096);
fclose($handle);
}
$allData = explode(',',$result);
$dollarValue = $allData[1];
$response['result']=$dollarValue;
$response['message']="value sent";
}
echo json_encode($response);
?>
JavaScript方法
function getData(from,to){
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr1 = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr1 = new ActiveXObject("Microsoft.XMLHTTP");
}
//path to your script
xhr1.open("GET", "http://localhost/practice/parse.php?from="+from+"&to="+to, true);
xhr1.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr1.send();
xhr1.onreadystatechange = display_data;
function display_data() {
if (xhr1.readyState == 4) {
console.log(xhr1.responseText);
//do what you want to do here
}
}
}