这是我的JS代码。这在IE中完美运行。如果我在浏览器中粘贴请求链接,那么我会得到JSON回复,但是当我运行此代码时。我没有得到雅虎或谷歌请求的任何答复。在IE中工作得非常好。
//var url1 = "http://finance.google.com/finance/info?client=ig&q=AAPL";
var yah_url1 = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("';
var yah_url2 = '")%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=';
function btn_stocks_click()
{
var div_table = document.getElementById("div_stock_table");
var btn_stocks = document.getElementById("btn_stocks");
div_table.style.display = (div_table.style.display == 'none') ? 'block' : 'none';
btn_stocks.value = (btn_stocks.value == "Show Stocks") ? "Hide Stocks" : "Show Stocks";
getJSONReply("AAPL");
}
function getJSONReply()
{
var req = yah_url1.concat(arguments[0]);
var url_req = req.concat(yah_url2);
alert(url_req);
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
alert(xhr.responseText.length);
}
}
xhr.open('GET', url_req, true);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET');
xhr.addEventListener("load", reqListener);
xhr.send();
}
function reqListener() // This was coded for Google Finance reply as it had other characters apart from reply.
{
var sub1 = this.responseText.substring(5,this.responseText.length);
var sub2 = sub1.substring(0, sub1.length - 2);
parse_JSON(sub2);
}
function parse_JSON()
{
var response = arguments[0];
alert(arguments[0]);
}
这是Chrome调试器中显示的错误
XMLHttpRequest无法加载http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20where%20symbol%20in%20%28%22AAPL%22%29%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env&format=json
对预检请求的响应未通过访问控制检查:否' Access-Control-Allow-Origin'标头出现在请求的资源上。起源' null'因此不允许访问。
答案 0 :(得分:0)
我使用WebClient
使用替代解决方案,使用ajax调用此方法转换货币
public JsonResult convertCurrencyUsingGoogle(decimal amount, string from, string to)
{
try
{
WebClient WebClient = new WebClient();
from = from.ToUpper();
to = to.ToUpper();
try
{
var CurrencyQuery = new StringBuilder();
CurrencyQuery.Append("https://www.google.com/finance/converter");
CurrencyQuery.AppendFormat("?a={0}", amount);
CurrencyQuery.AppendFormat("&from={0}", from);
CurrencyQuery.AppendFormat("&to={0}", to);
string response = WebClient.DownloadString(CurrencyQuery.ToString()); //response returns as page
var responsestring = response.Split(new string[] { "class=bld>" }, StringSplitOptions.None); // get element which contains money
var finalresponse = responsestring[1].Split(new string[] { to }, StringSplitOptions.None); // split curreny type
return Json(String.Format("{0:G29}", Convert.ToDecimal(finalresponse[0].Trim()))); //return currency
}
catch (Exception e)
{
return Json("error");
}
}
catch (Exception e)
{
return Json("error");
}
}