在服务之间访问数据与从另一个域调用在一个域上定义的JavaScript函数不同。
换句话说,我认为你混淆了“同源策略”(例如,我的浏览器中的一个选项卡阻止我在浏览器的另一个选项卡中调用在某个站点上定义的JS函数),JS从URL获取数据(例如来自雅虎的股票价格)。
这是你需要做的:JSONP。
由于所述政策,您不能向雅虎提出AJAX请求,但有一些解决方法。即脚本标记,可以向任何地方发出请求。
例如,假设您想在用户点击“开始”按钮时向雅虎发出请求。您需要添加一个事件处理程序来捕获用户的click事件,然后将新脚本标记添加到DOM的head部分。脚本标记的URL很重要,它必须有一个回调参数,例如:
http://helloasdf.cloudfoundry.com/get.tokens?callback=xss
注意回调可以是任意函数名。答复将是:
xss(["asdf"])
意味着你的代码中的xss函数将被传递[“asdf”]。
或者w / yahoo的API;
http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=GS&callback=YAHOO.Finance.SymbolSuggest.ssCallback
注意callback = YAHOO.Finance.SymbolSuggest.ssCallback它将在请求返回时调用该函数:
YAHOO.Finance.SymbolSuggest.ssCallback({"ResultSet":{"Query":"gs","Result":[{"symbol":"GS","name": "The Goldman Sachs Group, Inc.","exch": "NYQ","type": "S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"^GSPC","name": "S&P 500 INDEX,RTH","exch": "SNP","type": "I","typeDisp":"Index"},{"symbol":"GSS","name": "Golden Star Resources, Ltd.","exch": "ASE","type": "S","exchDisp":"AMEX","typeDisp":"Equity"},{"symbol":"^GSPTSE","name": "S&P/TSX Composite index (Interi","exch": "TOR","type": "I","exchDisp":"Toronto","typeDisp":"Index"},{"symbol":"GSK","name": "GlaxoSmithKline plc","exch": "NYQ","type": "S","exchDisp":"NYSE","typeDisp":"Equity"},{"symbol":"GSX","name": "Gasco Energy Inc.","exch": "ASE","type": "S","exchDisp":"AMEX","typeDisp":"Equity"},{"symbol":"OIL","name": "iPath S&P GSCI Crude Oil TR Index ETN","exch": "PCX","type": "E","typeDisp":"ETF"},{"symbol":"GSIC","name": "GSI Commerce Inc.","exch": "NMS","type": "S","exchDisp":"NASDAQ","typeDisp":"Equity"},{"symbol":"GST","name": "Gastar Exploration, Ltd.","exch": "ASE","type": "S","exchDisp":"AMEX","typeDisp":"Equity"},{"symbol":"GSI","name": "General Steel Holdings, Inc.","exch": "NYQ","type": "S","exchDisp":"NYSE","typeDisp":"Equity"}]}})
以下是动态添加脚本标记所需的js示例:
var headLoc = document.getElementsByTagName("head").item(0); var scriptObj = document.createElement("script"); var token="localstring" var url="http://helloasdf.cloudfoundry.com/get.tokens?callback=xssCallback"; // Add script object attributes scriptObj.setAttribute("type", "text/javascript"); scriptObj.setAttribute("charset", "utf-8"); scriptObj.setAttribute("src", url); scriptObj.setAttribute("id", 'asf12'); headLoc.appendChild(scriptObj);
我在这里更多地记录了这个过程: http://eggie5.com/22-circumvent-same-origin-policy
您可以使用Yahoo Finance JSONP ,所以这绝对是你正在使用的。
一个示例URL是......
http://d.yimg.com/autoc.finance.yahoo.com/autoc?query=Apple&callback=YAHOO.Finance.SymbolSuggest.ssCallback
加载请求后,它将调用您在GET参数中定义的回调。这可以让你解决 同源政策 ,前提是该服务支持JSONP。
或者,有些人使用他们的服务器作为代理。