从jQuery.get()为变量分配响应的正确方法是什么?
var data = jQuery.get("output.csv");
Run Code Online (Sandbox Code Playgroud)
我在读jQuery.get()必须有一个回调函数?这是为什么?以及如何使用此回调函数将响应分配回数据变量?
在此先感谢您的帮助和澄清.
更新:
谢谢大家的答案和解释.我想我开始最终掌握你们所说的话了.我的下面的代码只是在它的第一次迭代中做正确的事情.其余的迭代它写入页面未定义.我错过了什么吗?
<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>
Run Code Online (Sandbox Code Playgroud)
异步函数调用需要回调函数,例如AJAX GET请求.调用get
函数和获取响应之间存在延迟,这可能是毫秒或几分钟,因此您需要具有在异步GET完成其工作时调用的回调函数.
以下是有关jQuery的AJAX get
函数的更多信息:http: //docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype.
从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);
});
Run Code Online (Sandbox Code Playgroud)
如果您undefined
在尝试使用data
回调函数中的变量时获得,请在Firefox中的Firebug中打开控制台并观察get
请求.您可以看到原始请求及其返回的响应.在看到发送到服务器的内容以及发送回客户端的内容后,您应该更好地了解问题.
只需要在get方法的参数中指定回调函数即可。您的数据将位于您在函数中指定的变量中。
$.get("output.csv", function(data) {
// Put your function code here, the 'data' variable will hold your data.
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33334 次 |
最近记录: |