如何将动态变量添加到API链接?

时间:2017-03-22 13:47:47

标签: javascript jquery html ajax

我正面临一个问题,我希望通过将变量传递给它来使我的API链接成为动态链接。我的API是:http://api.fixer.io/latest?symbols=SGD,MYR 现在我想要最后两个值,即SGD& MYR作为我输入的输入字段的动态变量。那怎么做? 这是我的完整代码。



$(function(){
   $('button').on('click' , function(){
      var val1 = document.getElementById('value1').value;
      var val2 = document.getElementById('value2').value;

      var $records = $('#records');

      $.ajax({
	       type: 'GET' ,
               url: "http://api.fixer.io/latest?symbols="+val2+","+val1,  //value are not coming to the link 
               success: function(data) 
               {
                   console.log(val1);      // values are coming here
	           console.log(val2);     // values are coming here
         	   var rate1 = data.rates.val1 ;
        	   var rate2 = data.rates.val2 ;
        	   var final = rate1/rate2 ;
        	   $('#records').html ('Total Rate for Above Currency is :  ' + final ) ;
               }
            });
        });
   });

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body align="center"><br/><br/><br/>
<h1> Welcome Currency Convertor </h1> <br/><br/>
Local CCY : <input type="text" id="value1"> <br/><br/>
Hotel CCY : <input type="text" id="value2"> <br/><br/>
<button> Show rate </button> <br/><br/>
<div id="records"> </div>
</body>
</html>
&#13;
&#13;
&#13;

帮帮我。提前谢谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

&#13;
&#13;
$(function() {
  $('button').on('click', function() {
    var val1 = document.getElementById('value1').value;
    var val2 = document.getElementById('value2').value;
    var $records = $('#records');
    var composedUrl = "http://api.fixer.io/latest?symbols=" + val1 + "," + val2;

    console.log(composedUrl);

    $.ajax({
      type: 'GET',
      url: composedUrl,
      success: function(data) {

        var rate1 = data.rates[val1];
        var rate2 = data.rates[val2];

        console.log(rate1);
        var final = rate1 / rate2;
        $('#records').html('Total Rate for Above Currency is :  ' + final);
      }
    });
  });
});
&#13;
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body align="center"><br/><br/><br/>
  <h1> Welcome Currency Convertor </h1> <br/><br/> Local CCY : <input type="text" id="value1"> <br/><br/> Hotel CCY : <input type="text" id="value2"> <br/><br/>
  <button> Show rate </button> <br/><br/>
  <div id="records"> </div>
</body>

</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你应该删除最后一个+,如下所示:

url: "http://api.fixer.io/latest?symbols="+val1+","+val2,

因为事后没有任何事情发生。 现在它需要另一个变量或字符串,但没有