这是我在StackOverflow上的第一个问题。我正在研究如何将API用于学校作业,我找到了一个返回股票报价的API(来自Markit on demand) - 但我无法弄清楚如何更新JS以进行查询来自DOM的搜索结果。目前,它只搜索预定义的AAPL'符号 - 如何更新JS以查询搜索结果? 谢谢!
/**
* Version 1.0, Jan 2012
*/
var Markit = {};
/**
* Define the QuoteService.
* First argument is symbol (string) for the quote. Examples: AAPL, MSFT, JNJ, GOOG.
* Second argument is fCallback, a callback function executed onSuccess of API.
*/
Markit.QuoteService = function(sSymbol, fCallback) {
this.symbol = sSymbol;
this.fCallback = fCallback;
this.DATA_SRC = "http://dev.markitondemand.com/Api/v2/Quote/jsonp";
this.makeRequest();
};
/**
* Ajax success callback. fCallback is the 2nd argument in the QuoteService constructor.
*/
Markit.QuoteService.prototype.handleSuccess = function(jsonResult) {
this.fCallback(jsonResult);
};
/**
* Ajax error callback
*/
Markit.QuoteService.prototype.handleError = function(jsonResult) {
console.error(jsonResult);
};
/**
* Starts a new ajax request to the Quote API
*/
Markit.QuoteService.prototype.makeRequest = function() {
//Abort any open requests
if (this.xhr) { this.xhr.abort(); }
//Start a new request
this.xhr = $.ajax({
data: { symbol: this.symbol },
url: this.DATA_SRC,
dataType: "jsonp",
success: this.handleSuccess,
error: this.handleError,
context: this
});
};
new Markit.QuoteService("AAPL", function(jsonResult) {
//Catch errors
if (!jsonResult || jsonResult.Message){
console.error("Error: ", jsonResult.Message);
return;
}
//If all goes well, your quote will be here.
console.log(jsonResult);
//Now proceed to do something with the data.
$(".results").first().append("<p>Name: " + jsonResult.Name + "</p> <p>Symbol: " + jsonResult.Symbol + "</p><p>Last Price: " + jsonResult.LastPrice + "</p><p>Change: " + jsonResult.Change + "</p>");
/**
* http://dev.markitondemand.com
*/
});
&#13;
<!doctype html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<form id = "searchWrap">
Search Stocks
<input type = "text" id = "stock_search">
</form>
<button class="submit">submit</button>
<div class = "results">
</div>
</body>
</html>
&#13;
答案 0 :(得分:0)
Markit.QuoteService是你必须传递2个参数的主要内容 1报价 2是函数回调,以防它设法提取数据
将以下功能添加到您的代码中
var since = '2015-05-03T00:00:00'; // or any other valid value for a Date constructor
var sinceMs = new Date(since).getTime();
setInterval(function() {
var ms = (new Date().getTime() - sinceMs);
document.body.innerHTML = 'Seconds elapsed: ' + Math.round(ms / 1000);
}, 100);
在onsubmit事件中添加表单
function submitForm(){
stock = $('#stock_search').val();
Markit.QuoteService(sock,drawHtml);
return false;
}
function drawHtml(jsonResult){
$(".results").first().append("<p>Name: " + jsonResult.Name + "</p> <p>Symbol: " + jsonResult.Symbol + "</p><p>Last Price: " + jsonResult.LastPrice + "</p><p>Change: " + jsonResult.Change + "</p>");
}
没有Markit内容的完整工作示例:
<form onsubmit="return submitForm();">