如何根据用户输入进行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>