0

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

主文件

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>
4

1 回答 1

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));
}

然后在服务器端,我直接从请求正文中读取(对不起,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)

希望这可以帮助

于 2013-09-17T06:22:08.360 回答