AJAX URL更新 [英] AJAX URL update

查看:81
本文介绍了AJAX URL更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我肯定有一个简单的解决方案,但是我遇到了问题,

Im sure there is a simple solution for this but im having issues,

我有一个外部ajax.js文件,该文件具有如下的AJAX调用:

I have an external ajax.js file that has an AJAX call like so:

$(function() {
    $.ajax({
        url: url,
        success: function( data, status )

在AJAX调用之上,我有两个全局变量,分别是ticker和url,如下所示:

above the AJAX call I have got two global variables called ticker and url like so:

 var ticker = 'AAPL'
 var url = 'http://blahblahblah' + ticker

在我的HTML文件中,我有一个输入框,用户在其中输入股票代码(例如GOOG),然后单击将更新股票变量的按钮,以便使用新URL再次进行AJAX调用.

In my HTML file I have got an input box where the user types in a ticker symbol (e.g. GOOG) and clicks a button that would update the ticker variable so that the AJAX call is done again with the new URL.

 <form id="form">
            <h3>Enter the ticker symbol of the company you wish to view:</h3>
            <input type="text" id="userInput">
            <button onclick="myFunction()">Try it</button>
        </form>

        <script type="text/javascript" src="ajax.js">
        <script>
        function myFunction()
        {
                //old value
                alert(ticker);

                ticker = document.getElementById('userInput').value;

                //new value
                alert(ticker);
        }
        </script>

此代码更改了股票代码变量,但仍使用旧的股票代码网址执行AJAX调用.我认为它的分配不正确?我是AJAX的新手,但是我找不到在线解释此问题的任何教程.

This code changes the ticker variable but the AJAX call is still being performed with the old ticker url. I think its not being assigned properly? Im very new to AJAX but I cant find any tutorials online that explain this problem.

谢谢

推荐答案

据我从您发布的代码中可以看出,只有在加载页面时才调用ajax例程,这解释了为什么只有默认的网址/代码显示在结果中.

As far as I can tell from the code you've posted, your ajax routine is only being called when the page is loaded, which explains why only the default url / ticker is shown in the results.

您需要将ajax例程包装在一个函数中,并在用户输入符号后调用它:

You need to wrap the ajax routine in a function and call it after the user has inputted a symbol:

在您的ajax.js文件中:

In your ajax.js file:

function getSymbolInfo(ticker) { // consider passing ticker to this function instead of using a global var
    $.ajax({
        url: url + ticker,
        success: function( data, status ) {
           // show results
        }
    });
}

并且来自MyFunction:

And from MyFunction:

function myFunction()
{
    var ticker = document.getElementById('userInput').value;
    getSymbolInfo(ticker);

}

这篇关于AJAX URL更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆