我摸索了一点jQuery和Python,我试图显示一个非常简单的页面显示加载img,而一个长度的Python脚本得到我需要显示的信息。
当然,当Python脚本准备好时,我希望隐藏加载图像并在其位置显示Python脚本的结果。
到目前为止,我能够在谷歌的帮助下拼凑出我的网页:
<html>
<head>
<img id="img" src="loader.gif">
<script src="assets/js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
url: "http://localhost/test.py";
$.post(url, function(data){
$("#id").html(data);
});
$("#img").hide();
});
</script>
</head>
</html>
任何帮助将是非常感激的。谢谢!
这部分
$("#id").html(data);
表示jQuery用Python脚本的响应填充id为"id"的元素。问题是你没有一个包含id="id"
的元素。
您还需要做的是将$("#img").hide();
放入$.post
的成功处理程序中。这样,当$.post
完成时,图像被隐藏。在您当前的代码中,它被立即隐藏,因为$.post
是一个异步请求,因此任何其他代码都不会等待它。
你的代码应该看起来像这样:
<html>
<head>
<img id="img" src="loader.gif">
<div id="id"></div>
<script src="assets/js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function() {
url: "http://localhost/test.py";
$.post(url, function(data){
$("#id").html(data);
$("#img").hide();
});
});
</script>
</head>
</html>
注意我添加的<div>
(您可以用任何其他HTML元素替换它)。
由于不同的原因,您的$.post
请求有可能失败。目前,您只有一个成功处理程序,它只在请求成功时被调用。你可以像这样添加一个"unsuccess"处理程序:
$.post(url, function(data){
$("#id").html(data);
$("#img").hide();
})
.fail(function(response) {
alert('Error: ' + response.responseText);
// .. do something else ..
});
这对我来说很有效:
index . php
<!DOCTYPE html>
<html>
<head>
<title>Python Loading IMG Page</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" >
<script src="src/jquery-1.10.2.min.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<div id="loading">
<img src="src/loading.gif" alt="loading_icon" />
</div>
<div id="results"></div>
</div>
<script language="javascript" type="text/javascript">
var URL = 'cgi-bin/test.py';
function read(){
$('#loading').show();
$.get(
URL,
{},
function(result){
$('#loading').hide();
$('#results').html(result);
},
'text'
).fail(function() {
alert('Wrong Python URL');
});
}
read();
</script>
</body>
</html>
目录/test.py
#!/usr/bin/env python
print "Content-type: text/html'r'n"
print "'r'n"
print "This is where the text goes."
print "Make sure you use HTML tags."