如何根据用户输入进行API调用? [英] How to make an API call based on user input?

查看:53
本文介绍了如何根据用户输入进行API调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户单击提交"按钮时,我试图对这样的API进行AJAX调用.我想通过获取用户在文本框中输入的值来形成API调用的URL.

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>

身体看起来像这样,

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

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

</body>

$ url 是否起作用,或者我做错了什么?

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

这是我正在处理的代码的副本- http://jsbin.com/pizoruxoyo/edit?html,输出

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

推荐答案

解决问题的一种方法是用document.ready()包装整个脚本,或者将代码显式地放入函数中并赋予其特定名称,然后使用按钮的onlclick ="myFunction()"属性调用该函数.

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>

这里是演示的链接: http://jsbin.com/pohofegiko/edit?html,output

这篇关于如何根据用户输入进行API调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆