3

我正在尝试让(最新的)Web.py 和 AJAX 相互配合,但到目前为止我还没有多少运气。

长话短说,我在本地开发计算机上同时运行服务器端(Web.py)和客户端(Javascript),但不知何故,我所有的 AJAX GET 请求都显示为 OPTION 请求。根据我的阅读,这是典型的跨域请求案例,但由于我在 localhost 上运行它,我不确定发生了什么。

这是服务器端代码:

import web
import json

def make_text(string):
    return string

urls = ('/', 'mainScreen',
    '/update', 'update'
)

app = web.application(urls, globals())

global content
content = {'key1': 'value1', 'key2': 'value2'}

def getPayload():
    return content

class mainScreen:

    def GET(self):
        web.header('Content-Type', 'application/json')
        web.header('Access-Control-Allow-Origin', '*')
        web.header('Access-Control-Allow-Credentials', 'true')
        return getPayload()

    def OPTIONS(self):
        web.header('Content-Type', 'application/json')
        web.header('Access-Control-Allow-Origin', '*')
        web.header('Access-Control-Allow-Credentials', 'true')
        return getPayload()

class update:
    def POST(self):
        global content
        content = web.input(_method='post')
        return "DONE."


if __name__ == '__main__':
    app.run()

这是客户端代码:

<html>
    <head>
        <title>WTF</title>
        <script type="text/javascript" src="../static/jquery.js"></script>
        <script type="text/javascript">

            function dial()
            {
                console.log("Fire in the hole!");

                $.ajax({
                     url: 'http://0.0.0.0:8080',
                     contentType: 'application/jsonp',
                     timeout : 5000,
                     cache: false,
                     success: function (data) {
                        console.log('[ajax] Connection successful! ' + JSON.stringify(data));
                    },
                    error:function (jqXHR, textStatus, errorThrown){
                        console.log(JSON.stringify(jqXHR) + ' ' + textStatus +'  '+errorThrown );
                    }
                });

                console.log("Done.");
            }


            $(function() {
                dial();
            });

        </script>
    </head>
    <body>
        <div id="container"></div>
    </body>
</html>

这是 Firebug 的输出:

洞里开火!index.html(第 9 行)完成。
index.html (line 24) [ajax] 连接成功!""
index.html (第 17 行)

请注意,“”表示请求获得了空数据。

这是 Firebug 的网络面板显示的内容:

Firebug 的网络面板,显示请求

如果我打开 Firebug 指示数据存在的页面,但如果我很简单地http://0.0.0.0:8080/在任何浏览器上打开,数据就会按预期显示!这里发生了什么?

最后,这是 Web.py 的日志:

    hal@ubuntu:~/Desktop/tut$ python app.py
    http://0.0.0.0:8080/
    127.0.0.1:43796 - - [26/Jul/2013 11:14:59] "HTTP/1.1 OPTIONS /" - 200 OK

顺便说一句,我在 Ubuntu 12.04 LTS 中编码。

PS:我还尝试将 Web.py 中的响应标头更改为:

web.header('Content-Type', 'text/plain')

但它没有用。

PS2:将客户端脚本上的服务器地址更改为“127.0.0.1:8080”或“localhost:8080”也没有帮助。

4

1 回答 1

1

Nailed it.

The issue was on the client-side code. I remove the contentType from the request itself and it worked perfectly.

于 2013-07-26T13:36:45.487 回答