How to make an API call based on user input?

隐身守侯 提交于 2021-01-28 17:48:26

问题


I am trying to make an AJAX call to an API like this when the user clicks on the Submit button. I want to form the URL for the API call by getting value which the user enters to a text-box.

<script type = "text/javascript">

$("#submit").click(function(){
  var stock = $("#stocks").val();
  var url = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=" + stock;

 $.ajax({
    url: url,
    dataType: 'jsonp',
    success: function(results){
        var status = results.Status;
        var company = results.Name;
        $('#results').append(status + '. Company is: ' + company);
    }
});

});  

</script>

The body looks like this,

<body>
  <input id="stocks" />
  <button type="submit" id="submit">Submit</button>

  <div id="results"></div>

</body>

Will the $url work or am I doing something wrong?

Here is a copy of the code that I am working on - http://jsbin.com/pizoruxoyo/edit?html,output


回答1:


One way of solving the problem would be to wrap the whole script with document.ready() or explicitly putting your code inside a function giving it a specific name and then calling the function by using the onlclick="myFunction()" property of the button.

function loadDoc() {
   var stock = $("#stocks").val();
   var url = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?    symbol=" + stock;

   $.ajax({
       url: url,
       dataType: 'jsonp',
       success: function(results){
           var status = results.Status;
           var company = results.Name;
           $('#results').append(status + '. Company is: ' + company);
       }
   });
};

And this is how your button would be used to call the function:

<button type="button" onclick="loadDoc()">Request data</button>

Here is a link to the demo: http://jsbin.com/pohofegiko/edit?html,output




回答2:


Wrap your code in document ready function and place it at the bottom of the page:

<script type = "text/javascript">
$(function(){
$("#submit").click(function(){
  var stock = $("#stocks").val();
  var url = "http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=" + stock;
  console.log(stock);
 $.ajax({

    url: url,
    dataType: 'jsonp',
    success: function(results){
        var status = results.Status;
        var company = results.Name;
        $('#results').append(status + '. Company is: ' + company);

    }
});

});

});

</script>

demo here



来源:https://stackoverflow.com/questions/36349121/how-to-make-an-api-call-based-on-user-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!