[英]How to make an API call based on user input?
I am trying to make an AJAX call to an API like this when the user clicks on the Submit button. 当用户单击“提交”按钮时,我试图对这样的API进行AJAX调用。 I want to form the URL for the API call by getting value which the user enters to a text-box. 我想通过获取用户在文本框中输入的值来形成API调用的URL。
<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? $url
工作还是我做错了什么?
Here is a copy of the code that I am working on - http://jsbin.com/pizoruxoyo/edit?html,output 这是我正在处理的代码的副本-http://jsbin.com/pizoruxoyo/edit?html,输出
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>
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. 解决该问题的一种方法是用document.ready()包装整个脚本,或将代码明确地放在一个函数中并为其指定一个特定名称,然后使用该函数的onlclick =“ myFunction()”属性调用该函数。按钮。
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 这是演示的链接: http : //jsbin.com/pohofegiko/edit?html,输出
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.