开发者

Retrieve output of a Python program using AJAX

开发者 https://www.devze.com 2023-02-22 06:37 出处:网络
test.html {% extends \'base.html\' %} {% block extra_js %} <script language=\"Javascript\"> function xmlhttpPost(strURL) {

test.html

{% extends 'base.html' %}

{% block extra_js %}
<script language="Javascript">
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var form     = document.forms['f1'];
    var word = form.word.value;
    qstr = 'w=' + escape(word);  // NOTE: no '?' before querystring
    return qstr;
}

function updatepage(str){
    document.getElementById("result").innerHTML = str;
}
</script>

{% endblock %}

{% block main1 %}
<form name="f1">
  <p>word: <input name="word" type="text">  
  <input value="Go" type="button" onclick='JavaScript:xmlhttpPost("/site_media/rt.py")'></p>
  <div id="result"><开发者_开发问答;/div>
</form>
{% endblock main1 %}

rt.py

def ret():
    i=10
    return i

so when I click on Go button I want get i value 10 in div tag. but the output is like def ret(): i=10 return i

its just read rt.py and show on webpage.


What do you expect? That the string 10 appears in the page?

It will not, because you have the following problems:

  1. your web server is not configured to interpret Python programs (as it just returns the source code)
  2. your python code will not write anything to standard output, and a web server, after it ended processing the code, will usually return the standard output of the program to the HTTP client

Now, I suspect that you use Django, so it could not be a problem of web server but just a configuration problem. In this case, please follow the Django tutorial that corresponds to your Django version, and you'll understand that you have to configure an URL, map it to an application and write there your response.

If you don't use Django, just fix the web server and your python code as I (shortly) explained.

0

精彩评论

暂无评论...
验证码 换一张
取 消