AJAX请求无法工作GAE

2024-05-18 19:14:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在关注来自here的tut,但是我不能让ajax工作,我也检查了chromes控制台中的头,但是我也没有看到text/json头!你能帮我一下吗?我想不通。 提前谢谢。你知道吗

主.py

class Main(webapp2.RequestHandler):
def get(self):
    if self.request.get('fmt') == 'json':
        data = {'name' : 'sam', 'age': 25}
        self.response.headers['content-type'] = 'text/json'
        self.response.write(json.dumps(data))
        return
    self.templateValues = {}
    self.templateValues['title'] = 'AJAX JSON'
    template = jinja_environment.get_template('index.html')
    self.response.write(template.render(self.templateValues))

app = webapp2.WSGIApplication([('/.*', Main),], debug=True)

索引.html

<input type ="button" id="getitbutton" value="click button"/>
<div id= "result">
</div>

js脚本

<script  type="text/javascript" >
function showData(data){
    console.log(data.name);
    $('#result').html(data.name)
}
function handleclick(e){
    $.ajax('/',{
        type: 'GET',
        data: {
            fmt: 'json'
        }
        success: showData
    });
}
$(document).ready(function(){
    $('#getitbutton').on('click', handleclick);
});
</script>

Tags: textnameselfjsondatagetmainresponse
1条回答
网友
1楼 · 发布于 2024-05-18 19:14:14

当前的浏览器存在一些问题,特别是IE不发送text/json内容类型头。所以我学会了不依赖标题。你知道吗

相反,我的解决办法是:

js ajax函数:

function ajax(url,obj,callback){
    var xhr=new XMLHttpRequest;
    xhr.onreadystatechange=function(){
        if(this.readyState==4){
            if(callback){
                callback(this.responseText);
            }
        }
    }
    xhr.open("POST",url);
    xhr.send(JSON.stringify(obj));
}

然后在服务器端,我直接从请求体中读取内容(很抱歉使用Go代码,但我认为您也可以从Python运行时获取请求体?)地址:

// read the request body
body, _ := ioutil.ReadAll(httpRequest.Body)

// parse the json payload
var user struct {
        Email    string
        Password string
}
json.Unmarshal([]byte(body), &user)

希望这有帮助

相关问题 更多 >

    热门问题