2015-11-20 21 views
-4

請幫我弄清楚這個php代碼的javaScript/jQuery等價物。php到javaScript

<?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; 
+0

這是正確的? –

+0

$ url ='http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='。 $從。 $ to。'= X'; –

+0

@Azmatkarim我已經手動輸入了包含在瀏覽器中的變量的URL,並且它工作正常 – user3476732

回答

1

嘗試......

您可以使用jQuery AJAX將值傳遞到PHP頁面,並從阿賈克斯成功獲取輸出。

$.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/

0

的的fopen在這種情況下的等效會像做一個jQuery的Ajax的GET請求,但是由於finance.yahoo.com是在不同的域上,並且他們的服務器不允許跨域請求,GET請求會出錯。爲了解決這個問題,你需要將PHP腳本放在同一個域上,並對此做出請求。

0

保存腳本服務器上

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 
      } 
} 

}