【问题标题】:AJAX request not working GAEAJAX 请求不起作用 GAE
【发布时间】:2013-09-21 02:20:02
【问题描述】:

我正在关注here 的 tut,但我无法让 ajax 工作,我也检查了 chromes 控制台中的标题,但我也没有看到 text/json 标题!你能帮我解决一下吗,我想不通。 提前致谢。

ma​​in.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)

index.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>

【问题讨论】:

    标签: javascript python ajax google-app-engine python-2.7


    【解决方案1】:

    当前浏览器存在一些问题,尤其是 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));
    }
    

    然后在服务器端,我直接从 Request Body 中读取(抱歉 Go 代码,但我认为您也可以从 Python runtime 获取 Request body?):

    // 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)
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2014-05-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 2012-11-28
      • 2014-12-28
      • 2017-02-11
      • 2016-05-08
      • 2015-09-08
      相关资源
      最近更新 更多