2016-11-04 77 views
1

我正在摸索與jQuery和Python一點點,我試圖顯示一個非常簡單的頁面顯示加載IMG,而有點長的Python腳本獲取我需要顯示的信息。jQuery加載img,而exec Python腳本PHP

當然,當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> 

任何幫助將greately讚賞。謝謝!

+0

沒有ID爲「id」的元素 – simon

回答

1

這工作很適合我:

的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> 

的cgi-bin/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." 
2

這部分

$("#id").html(data); 

意味着jQuery是填充的ID「ID」從你的Python腳本響應中的元素。問題是你沒有一個有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元素替換它)。

UPDATE

有你$.post要求因不同原因未能機會。目前,您只有一個成功處理程序,只有在請求成功時纔會被調用。您可以添加一個 「不成功」 的處理程序是這樣的:

$.post(url, function(data){ 
    $("#id").html(data); 
    $("#img").hide(); 
}) 
.fail(function(response) { 
    alert('Error: ' + response.responseText); 
    // .. do something else .. 
}); 
+0

謝謝西蒙。但是,它似乎並沒有隱藏加載圖像,也沒有輸出python文本。是否有可能是因爲python文本沒有得到輸出它卡在那裏,爲什麼它也沒有隱藏img? – user5740843