我在 java 脚本中有一个函数,我用它从我的 asp.net mvc Controller 获取 JSON,以在我的 View 中显示该项目:
<script type="text/javascript" language="javascript">
var k = 0;
var record_count = 0;
var col_count = 3;
var row_count = record_count / col_count;
var str = "<table>";
function itemTemplate() {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, function (product) {
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
});
str += '</table>';
alert(str);
return (str);
}
$(document).ready(function () {
alert(itemTemplate());
});
</script>
问题:当我向 $(document).ready
中的函数发出警报时功能,首先是alert <table></table>
然后继续提醒我将其连接到我的 $.getJSON
中的完整字符串功能。所以该函数是在获取 JSON 之前返回。
有人对此有任何想法吗? 谢谢。
最佳答案
尝试将 async
设置为 false,然后进行 $.getJSON
调用
代码:
jQuery.ajax({async : false});
$.getJSON( ... );
引用:http://api.jquery.com/jQuery.ajax/
注意:从 jQuery 1.8 开始,不推荐使用 async: false。
替代解决方案
<script type="text/javascript" language="javascript">
var k = 0;
var record_count = 0;
var col_count = 3;
var row_count = record_count / col_count;
//var str = "<table>";
function itemTemplate(callback) {
var url = '<%: Url.Content("~/") %>' + "ProductListing/AllProductListing/0";
$.getJSON(url, callback);
//str += '</table>';
//alert(str);
//return (str);
}
$(document).ready(function () {
itemTemplate(function (product) {
var str = "<table>";
$.each(product.ja, function (index, value) {
//append rows and column to my table by concat the string of 'str'
});
str += "</table>";
alert(str);
});
});
</script>
关于javascript - 在 JavaScript 中从 JSON 加载内容之前返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11237538/