开发者社区> 问答> 正文

请求PYTHON的WEB微框架BOTTLE处理AJAX的问题? 400 报错

请求PYTHON的WEB微框架BOTTLE处理AJAX的问题? 400 报错 BOTTLE的说明文档里有这样一段代码:

#coding='utf-8' from bottle import route,run,response,request,CherryPyServer html=''' <html> <head> <title>AJAX测试</title> <script type="text/javascript"> var xmlHttp;

function createXMLHttpRequest(){ if(window.ActiveXObject){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP") } else if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); } }

function startRequest(){ createXMLHttpRequest(); xmlHttp.onreadystatechange=handleStateChange; xmlHttp.open("GET","ajax",true); xmlHttp.send(null); }

function handleStateChange(){ if(xmlHttp.readyState==4){ if(xmlHttp.status==200){ alert("The server replied with:" + xmlHttp.responseText); } } } </script> </head> <body> <form action="#"> <input type="button" value="Start Basic Asynchronous Request" onclick="startRequest();" /> </form> </body> </html> ''' @route("/") def hello():     return html @route("/ajax") def ajax():     #if request.headers.get('X-Requested-With')=='XMLHttpRequest':     if request.is_xhr:         return 'This is an AJAX request'     else:         return 'Not An AJAX request!'

run(host='0.0.0.0',port = 80)  




我试了一下,发现得到的结果总是 ’This is a normal request’
我修改代码让程序遍历了一下request.headers,发现根本就没有’X-Requested-With’这个key。
不知道有没有人遇到过这样的问题,是我用的不对还是框架的问题。
是否还有别的办法来判断一个请求是否为AJAX请求?
请各位前辈帮忙,谢谢!

展开
收起
爱吃鱼的程序员 2020-06-04 16:30:04 623 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    你用jquery 试 就可以了  你的脚本请求  没有加头信息 

    xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest' );

    ######太感谢了,原来直接用js发送请求还需要加这个东西,终于明白了。现在还用jquery来发送了,果然简单了好多。以后有时间要好好学学了######

    http://www.w3school.com.cn/tiy/t.asp?f=jquery_ajax_post

    你用firebug或者chrome的控制台,会发现ajax的header的确带有X-Requested-With: XMLHttpRequest。

    所以上面代码没写错的话肯定成功的。

    仔细看看是哪里遗漏?


    ######谢谢,我的代码是照BOTTLE说明文档和AJAX基础教材写的,应该没有问题才对,我把代码补全。######

    http://www.bottlepy.org/docs/dev/_modules/bottle.html#BaseRequest.is_xhr

    if request.is_xhr: pass 

    ######谢谢,这个方法我也试过了,结果还是一样,判断不了AJAX请求。
    2020-06-04 17:10:21
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载