【发布时间】:2019-10-14 13:11:50
【问题描述】:
我正在努力弄清楚为什么当我进行 ajax POST 调用以填充 div 时 - 当我从 HTML 文档的同一个 SCRIPT 块中进行调用时,它显示得很好,但只要我将相同的调用作为函数移到单独的 .js 文件中,在 DIV 中没有呈现任何内容。
我确定我只是忽略了一些东西,但无法弄清楚是什么???
以下 WORKS(同一脚本块中的 ajax 调用)
<div id="flow">
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
{
data: JSON.stringify(
{
"some_json":
{
"id": 0,
...
}
}
),
contentType: 'application/json',
type: 'POST',
success: function(data){
$("#flow").html(data);
}
});
});
</script>
</body>
</html>
但是,如果我将调用移到单独的 .js 文件中的函数,它不会显示任何内容,即使我可以看到响应按预期返回(例如,DevTools 的网络选项卡正在查看对外部服务的调用我可以看到有效的 HTML 或预览)
以下内容不起作用(没有错误,但 DIV 中不显示任何内容)
<div id="flow">
</div>
<script type="text/javascript" src="assets/js/statusPanelMultiVersion.js"></script>
<script type="text/javascript">
$(document).ready(function() {
statusPanelMultiVersion('#flow',
{
"some_json":
{
"id": 0,
...
}
}
);
});
</script>
</body>
</html>
statusPanelMultiVersion.js
function statusPanelMultiVersion(_dom_obj, _data_objects) {
$.ajax( "http://localhost:8680/jsdv-status-panel/tsv-multi-version",
{
data: JSON.stringify(_data_objects),
contentType: 'application/json',
type: 'POST',
dataType: 'json',
success: function(data){
$(_dom_obj).html(data);
}
});
};
有趣的是,我在一个执行 ajax GET 的外部文件中有一个类似的函数 - 它按预期工作(结果在 DIV 中呈现)
function statusPanelLastValue(_dom_obj, _params) {
$.ajax( "http://localhost:8680/jsdv-status-panel/tsv-last-value" + _params,
{
contentType: 'application/json',
type: 'GET',
success: function(data){
$(_dom_obj).html(data);
}
});
};
这样称呼
statusPanelLastValue("#pool", "?biglongquerystring");
我要么没有看到明显的东西,要么不理解进行 POST 调用的 function() 和内联代码之间的区别。谁能看到我做错了什么?
【问题讨论】:
-
你能添加错误吗:function(data){ alert(data) } - 你可能会遇到一个错误并且成功永远不会触发。如果出错,我们可以更好地调试。
-
一件事...如果您将 JSON 转储到 div 上,获取 JSON 的目的是什么?你确定你的 POST 返回一个 JSON 吗?
-
卡洛斯,你的问题提示我看到问题!我没有注意到请求中的 dataType 和 ContentType 不正确。如果您没有发布答案,不确定如何给您信用