【问题标题】:jquery.post() and backend responded, but parameter of the callback function is emptyjquery.post() 和后端响应,但回调函数的参数为​​空
【发布时间】:2014-03-24 18:18:58
【问题描述】:

Linux bogon 3.9.5-301.fc19.i686,nginx1.4.2 + web.py0.37 + uwsgi2.01

我编写了一个获取用户输入(文本字符串)的 html 页面,并将其发布到后端。后端只是读取输入字符串并发送回页面。

<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery("#ExtButton").click(function(){
        var postdata = document.getElementById("url_to_get").value;
        jQuery.ajax({
            type: 'POST',
            url: "http://127.0.0.1/TextPickup",
            data: postdata,
            success: function(data,status){alert("status:"+ status +",data:" +data)},
            dataType:'html'
        });
    });
}); 
</script>
<input type="text" name="url_to_get" id="url_to_get" style="width:310px">
<button id="ExtButton">send</button>

和后端的python脚本:

import web
import os
urls = (
'/','Index',
'/TextPickup','TextPickup',
'/TextAnalysis', 'TextAnalysis'
)

class Index:
    ...

class TextPickup:
    def POST(self):
        dest_url = web.data()
        return dest_url + ".."

class TextAnalysis:
    ...

但是当我放东西并点击按钮时,数据是空的,如下所示:

我已经检查了 uWSGI 的输出,

[pid: 20807|app: 0|req: 1/1] 127.0.0.1 () {50 vars in 800 bytes} [Sun Feb 23 13:44:58 2014] POST /TextPickup => generated 6 bytes in 2 msecs (HTTP/1.1 200) 0 headers in 19 bytes (2 switches on core 0)

甚至是wireshark: 很明显,后端已成功发送响应,包括字符串“test..”,但为什么回调函数没有将响应字符串作为其参数?

更新: 在萤火虫中, 当我右键单击http://127.0.0.1/TextPickup 并选择“在新选项卡中打开”时, 出现了一个包含预期字符串“test..”的页面。但是,它应该是回调函数的参数。

【问题讨论】:

  • 你能用浏览器开发者工具的网络标签检查响应吗
  • 既然你发送的是纯文本,你可以试试 dataType : 'text'
  • 看起来您的 python 脚本正在以十六进制形式返回它,否则在您的“wireshark”响应区域中它会以字符串形式返回您的响应。尝试将您的 dest_url var 显式转换为字符串(对不起,如果这是错误的,我以前从未使用过 python,所以这只是一个猜测)
  • @ArunPJohny 我已经尝试使用 firebug 来检查响应,但仍然无法弄清楚
  • @palanik 'text' 和 'html' 都不起作用

标签: javascript jquery python http web.py


【解决方案1】:

我找到了为什么不起作用--web.py使用不正确,浏览网页也错误

首先,我将文件整理如下:

folder1
--GetText.html
--cgi-bin
    --TextAnalysis.py

只需单击文件 GetText.html 即可访问网页。 错误发生了。

我看了一些关于web.py和jQuery的页面,比如random Bytes,甚至一个论坛的源代码使用了github上的web.py和jQuery,发现/template文件夹不是必须的。

现在我像这样重新排列文件

folder1
--TextAnalysis.py
--templates
    --GetText.html

因此 GetText.html 中的 jquery.post() 更改为

jQuery.ajax({
    type: 'POST',
    url: "/TextPickup",
    data: postdata,
    success: function(data){alert(data);},
    dataType:'text'
});

TextAnalysis.py:

class Index:
    def GET(self):
    return render.GetText()

...

render = web.template.render('templates/') #add up

现在我通过在 Firefox 中输入 url http://127.0.0.1/ 来访问网页,一切正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2019-11-07
    • 1970-01-01
    • 2020-09-02
    相关资源
    最近更新 更多