【问题标题】:Passing a value obtained in asynchronous function to index.html?将异步函数中获得的值传递给 index.html?
【发布时间】:2014-06-03 15:01:59
【问题描述】:

我目前正在开发我的第一个 Web 应用程序,用户可以在其中选择股票并使用 AJAX 实时获取股票数据。

我目前已经设置好了,这样用户就可以选择一只股票并从数据库中获取信息(参见 3weekwebsites.com 上的演示),但是现在我正在尝试用同样的方法构建一个图表,这被证明是显着的更加困难。这是因为在我可以使用 javascript 显示结果之前,但是现在我需要制作图表的代码在我的 index.html 中,据我所知,您无法传递异步函数的返回值。

HTML

getStock("aapl");

<script>
var chartData = [];
        function createStockChart() {
            ...
            chart.dataProvider = chartData;     
            chart.write('chartdiv');
        }

</script>  
<body>
    <div id="chartdiv" style="width:100%; height:500px;"></div>
</body>

Javascript

var stock;

function getStock(str)
    {   
        if (window.XMLHttpRequest)
        {
            // Create the object for browsers
            xmlhttp=new XMLHttpRequest();
        }
        else
        {
            // Create the object for browser versions prior to IE 7
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            // if server is ready with the response
            if (xmlhttp.readyState==4) 
            {
                // if everything is Ok on browser
                if(xmlhttp.status==200) 
                {    
                    stock = xmlhttp.responseText.split(",");
                    alert("Can I pass this value along somehow:" + stock);
                }
            }
        }
        //send the selected option id to the php page 
        xmlhttp.open("GET","query.php?symbol="+str,true);
        xmlhttp.send();
    }

如您所见,我想传递在我的 javascript 文件中获得的值(变量“stock”),以便我可以在 index.html 或最终在另一个 javascript 文件中设置我的图表数据。我尝试制作一个回调函数来移动变量,但是我似乎无法让它工作,因为回调函数也是异步的。我在这里错过了什么吗?任何帮助将不胜感激,谢谢。

【问题讨论】:

  • jQuery 标签的作用是什么?
  • 对不起,我是智障,我以为那里有 jQuery...>.
  • 别担心,欢迎加入! ;)

标签: javascript jquery ajax asynchronous argument-passing


【解决方案1】:

如果我理解你的问题,你可以更改 JS 文件中的函数以将回调函数作为参数...

function getStock(str, callback){
     //make request and if status 200 makea call to callback function
     if(xmlhttp.status==200) 
            {    
                stock = xmlhttp.responseText.split(",");
                alert("Can I pass this value along somehow:" + stock);
                callback(stock);
            }
}

在 HTML 文件中,传递回调函数...

getStock("aapl", createStockChart);
<script>
   var chartData = [];
    function createStockChart(stockVal) {
        ...
        chart.dataProvider = chartData;     
        chart.write('chartdiv');
        //use stockVal
    }

</script> 

【讨论】:

  • 谢谢!我还意识到我可以将 index.html 中的 javascript 代码移动到实际的 javascript 文件中......然后我可以写 - 成功:createStockChart();以便该函数在 php 脚本完成后执行。感谢您的帮助,我将进一步研究回调函数:)
猜你喜欢
  • 2015-09-24
  • 2020-01-04
  • 2020-08-03
  • 2015-12-01
  • 2021-12-29
  • 1970-01-01
  • 2022-12-22
  • 1970-01-01
  • 2015-06-13
相关资源
最近更新 更多