将 jQuery.get() 分配给变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1244374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:59:34  来源:igfitidea点击:

Assign jQuery.get() to a variable?

ajaxjquerycallback

提问by

What is the correct way of assigning to a variable the response from jQuery.get() ?

将来自 jQuery.get() 的响应分配给变量的正确方法是什么?

var data = jQuery.get("output.csv");

I was reading that jQuery.get() must have a callback function? why is that? and how would i use this callback function to assign the response back to the data variable?

我在读 jQuery.get() 必须有一个回调函数?这是为什么?我将如何使用此回调函数将响应分配回数据变量?

Thanks in advance for your help and clarification.

在此先感谢您的帮助和澄清。

Update:

更新

Thank you all for your answers and explanations. I think i am starting to finally grasp what you are all saying. My code below is doing the right thing only the first iteration of it. The rest of the iterations its writing to the page undefined. Am i missing something?

谢谢大家的回答和解释。我想我终于开始明白你们在说什么了。我下面的代码只是在它的第一次迭代中做正确的事情。其余的迭代将其写入未定义的页面。我错过了什么吗?

<tbody>
<table id="myTable"> 

    <script type="text/javascript">

        $.get('output.csv', function(data) {
                csvFile = jQuery.csv()(data);

                for ( var x = 0; x < csvFile.length; x++ ) {
                    str = "<tr>";
                    for ( var y = 0; y < csvFile.length; y++) {
                        str += "<td>" + csvFile[y][y] + "</td>";
                    }
                    str += "</tr>";
                }
                $('#myTable').append(str);


        });

    </script>

</tbody>
</table>

回答by Tim S. Van Haren

A callback function is required for asynchronous function calls, like an AJAX GET request. There is a delay between calling the getfunction and getting a response back, which could be a millisecond or several minutes, so you need to have a callback function that gets called when the asynchronous GET has completed its work.

异步函数调用需要回调函数,例如 AJAX GET 请求。在调用get函数和得到响应之间有一个延迟,可能是一毫秒或几分钟,所以你需要有一个回调函数,当异步 GET 完成其工作时被调用。

Here's some more info on jQuery's AJAX getfunction: http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype.

这里有一些关于 jQuery 的 AJAXget函数的更多信息:http: //docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype

From jQuery's examples:

从jQuery的例子:

// this would call the get function and just 
// move on, doing nothing with the results
$.get("test.php");

// this would return the results of the get
$.get("test.php", function(data){
  alert("Data Loaded: " + data);
});

If you get undefinedwhen you try to use the datavariable in the callback function, open up the console in Firebug in Firefox and watch the getrequest. You can see the raw request and the response that it comes back with. You should get a better indication of the issue after seeing what's being sent to the server and what's being sent back to the client.

如果您undefined尝试data在回调函数中使用该变量时出现,请在 Firefox 中的 Firebug 中打开控制台并查看get请求。您可以看到原始请求和它返回的响应。在查看发送到服务器的内容和发送回客户端的内容后,您应该对问题有更好的指示。

回答by Elzo Valugi

Actually in your example the data will be the XMLHttpRequest request object.

实际上,在您的示例中,数据将是 XMLHttpRequest 请求对象。

var x;
$.get( 'output.csv', function(data){
    x = data;
    console.log(x); // will give you the contents.
});

回答by CityPickle

I really struggled with getting the results of jQuery ajax into my variables at the "document.ready" stage of events.

在事件的“document.ready”阶段,我真的很难将 jQuery ajax 的结果放入我的变量中。

jQuery's ajax would load into my variables when a user triggered an "onchange" event of a select box after the page had already loaded, but the data would not feed the variables when the page first loaded.

当用户在页面加载后触发选择框的“onchange”事件时,jQuery 的 ajax 将加载到我的变量中,但在页面首次加载时数据不会提供变量。

I tried many, many, many different methods, but in the end, the answer I needed was at this stackoverflow page: JQuery - Storing ajax response into global variable

我尝试了很多很多不同的方法,但最后,我需要的答案是在这个 stackoverflow 页面上:JQuery - 将 ajax 响应存储到全局变量中

Thanks to contributor Charles Guilbert, I am able to get data into my variables, even when my page first loads.

感谢贡献者 Charles Guilbert,即使我的页面第一次加载,我也能够将数据放入我的变量中。

Here's an example of the working script:

这是工作脚本的示例:

    jQuery.extend
    (
       {
          getValues: function(url) 
          {
              var result = null;
              $.ajax(
              {
                url: url,
                type: 'get',
                dataType: 'html',
                async: false,
                cache: false,
                success: function(data) 
                {
                    result = data;
                }
              });
          return result;
          }
       }
    );

// Option List 1, when "Cats" is selected elsewhere
optList1_Cats += $.getValues("/MyData.aspx?iListNum=1&sVal=cats");

// Option List 1, when "Dogs" is selected elsewhere
optList1_Dogs += $.getValues("/MyData.aspx?iListNum=1&sVal=dogs");

// Option List 2, when "Cats" is selected elsewhere
optList2_Cats += $.getValues("/MyData.aspx?iListNum=2&sVal=cats");

// Option List 2, when "Dogs" is selected elsewhere
optList2_Dogs += $.getValues("/MyData.aspx?iListNum=2&sVal=dogs");

回答by Clinton Pierce

tsvanharen answered the question well, but DCrawmer's still missing the point. Let me attempt a clarification for him. I'm oversimplifying some of this, and smoothing over some details.

tsvanharen 很好地回答了这个问题,但 DCrawmer 仍然没有抓住重点。让我试着为他澄清一下。我过度简化了其中的一些,并平滑了一些细节。

Look at the code shown below. This is pretty much the same code as tsvanharen's, except that I've replaced the anonymous function for the callback with an actual function pointer, and am a little more explicit so you can see what's going on:

看看下面显示的代码。这与 tsvanharen 的代码几乎相同,只是我用实际的函数指针替换了回调的匿名函数,并且更加明确,因此您可以看到发生了什么:

var x = null;

function myCallback(data)
{
   alert("Data Loaded:" + data);
}

$.get("test.php", myCallback);

// the rest of your code
alert("The value of X is: " + x);

Assuming that test.php takes even a moment or two to load, notice the order that the alerts probably come up in:

假设 test.php 甚至需要一两分钟来加载,请注意警报可能出现的顺序:

1. "The value of X is"
2. "Data Loaded"

The function $.get()runs instantaneously. JavaScript moves on and runs the rest of your code right away. In the background, it's retrieving your page at test.php. jQuery hides some of the messy details of this.

该功能$.get()立即运行。JavaScript 继续运行并立即运行其余代码。在后台,它会在 test.php 中检索您的页面。jQuery 隐藏了一些混乱的细节。

The callback function (the second argument to $.get()) runs later (asynchronously). Or, said another way, the function myCallbackis a handler to an event. That event is "$.get()has finished retrieving the data". It doesn't get run until that point. It doesn't run when $.get()runs! $.get()just remembers where that function is for later.

回调函数(第二个参数$.get())稍后运行(异步)。或者,换句话说,该函数myCallback是一个事件的处理程序。该事件是“$.get()已完成检索数据”。直到那时它才开始运行。运行时不运行$.get()$.get()只记得该功能用于以后的位置。

The function myCallbackmay run milliseconds or minutes later, long after $.get()has been dealt with.

该函数myCallback可能会在几毫秒或几分钟后运行,在$.get()处理很久之后。

If myCallbackdoesn't run until minutes later, then what's the value of x when the "The value of X" code is run? It's still null. There's your bug.

如果myCallback直到几分钟后才运行,那么运行“X 的值”代码时 x 的值是多少?还是null这是你的错误

To use the data retrieved from the page in your script, you have to do things more like this:

要在脚本中使用从页面检索到的数据,您必须执行以下操作:

  1. Start your script, declare your variable to hold the data.
  2. Call $.get(), with a callback function to handle the return.
  3. Do nothing else. [Or, at least, nothing that requires the data] Let the page just sit there.

    ...sometime in the future...

    X. Your callback function will get run, and have the results of your web page. Your callback function can: * Display the data * Assign that data to a variable * Call other functions * Go along it's merry way.

  1. 启动你的脚本,声明你的变量来保存数据。
  2. 调用$.get(),带有回调函数来处理返回。
  3. 什么都不做。[或者,至少,不需要数据的任何东西]让页面就在那里。

    ……在未来的某个时候……

    X. 您的回调函数将运行,并获得您网页的结果。你的回调函数可以: * 显示数据 * 将该数据分配给一个变量 * 调用其他函数 * 继续它的快乐方式。

回答by googletorp

You just need to specify the callback function in the parameter to get method. Your data will be in the variable you specify in the function.

你只需要在get方法的参数中指定回调函数即可。您的数据将位于您在函数中指定的变量中。

$.get("output.csv", function(data) {
    // Put your function code here, the 'data' variable will hold your data.
});