将 jQuery.get() 的响应分配给变量的正确方法是什么?
var data = jQuery.get("output.csv");
我读到 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>
最佳答案
异步函数调用需要回调函数,例如 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);
});
如果当您尝试在回调函数中使用 data
变量时得到 undefined
,请在 Firefox 中的 Firebug 中打开控制台并观看 get
请求。您可以看到原始请求及其返回的响应。在查看发送到服务器的内容以及发送回客户端的内容后,您应该可以更好地了解问题。
关于ajax - 将 jQuery.get() 分配给变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1244374/