AJAX Form POST Request - HTML Form POST/Submit with AJAX

本文介绍如何利用AJAX技术实现HTML表单的数据发送及服务器响应展示,无需刷新页面即可完成交互过程,包括AJAX的工作原理、实现代码及应用场景。
NOTE: It is not possible to make file uploads with AJAX, since Javascript does not have access to local files! If you want to upload files, you still need to utilize e.g. an iFrame or submit the form the regular way.

UPDATE: In order to avoid a syntax error in Firefox, if the returned content is NOT valid XML, use the overrideMimeType method to set the content-type.
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');



AJAX is the new hype in HTML/Javascript, since Google came up with their nifty GMAIL application. AJAX allows to write web-applications without reloading/refreshing the page on user interaction (e.g. posting data to a server-side script). The traditional way of processing HTML forms was to submit them to the server, the server processed the data and sent a response. The drawback of this method is that the page was reloaded in the browser.

With AJAX the browser page is not reloading, but the data is just sent to the server for processing. The server saves the data or calculates something and sends back the answer. The AJAX javascript either displays the answer (page) or does some action depending on the answer.

This example demonstrates a simple AJAX javascript for POSTing a complete HTML form to the server and displaying the response. The server-response is displayed in a "span" - the server-side script is a simple PHP script to display the contents of the $_POST global variable.

<script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"> </script>
UPDATE:
I've updated the form - now it also works with a normal submit button and also when the user just presses enter!

Test the whole hack here:




Server-Response:





post.html:
<script type="text/javascript" language="javascript">
   var http_request = false;
   function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj) {
      var poststr = "mytextarea1=" + encodeURI( document.getElementById("mytextarea1").value ) +
                    "&mytextarea2=" + encodeURI( document.getElementById("mytextarea2").value );
      makePOSTRequest('post.php', poststr);
   }
</script>


<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
<textarea id="mytextarea1">my test
1
2
3
</textarea>
<textarea id="mytextarea2">my test2
4
5
6</textarea>
<br>
<input type="button" name="button" value="Submit" 
   onclick="javascript:get(this.parentNode);">
<input type="submit" name="button" value="Normal Submit Button">
</form>

<br><br>
Server-Response:<br>
<hr>
<span name="myspan" id="myspan"></span>
<hr>

post.php
<?
print_r(NOTE: It is not possible to make file uploads with AJAX, since Javascript does not have access to local files! If you want to upload files, you still need to utilize e.g. an iFrame or submit the form the regular way. 

UPDATE: In order to avoid a syntax error in Firefox, if the returned content is NOT valid XML, use the overrideMimeType method to set the content-type.
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');



AJAX is the new hype in HTML/Javascript, since Google came up with their nifty GMAIL application. AJAX allows to write web-applications without reloading/refreshing the page on user interaction (e.g. posting data to a server-side script). The traditional way of processing HTML forms was to submit them to the server, the server processed the data and sent a response. The drawback of this method is that the page was reloaded in the browser.

With AJAX the browser page is not reloading, but the data is just sent to the server for processing. The server saves the data or calculates something and sends back the answer. The AJAX javascript either displays the answer (page) or does some action depending on the answer.

This example demonstrates a simple AJAX javascript for POSTing a complete HTML form to the server and displaying the response. The server-response is displayed in a "span" - the server-side script is a simple PHP script to display the contents of the $_POST global variable.
___FCKsi___1
UPDATE:
I've updated the form - now it also works with a normal submit button and also when the user just presses enter!

Test the whole hack here:




Server-Response:

___FCKsi___4
post.html:
<script type="text/javascript" language="javascript">
   var http_request = false;
   function makePOSTRequest(url, parameters) {
      http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         http_request = new XMLHttpRequest();
         if (http_request.overrideMimeType) {
         	// set type accordingly to anticipated content type
            //http_request.overrideMimeType('text/xml');
            http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      
      http_request.onreadystatechange = alertContents;
      http_request.open('POST', url, true);
      http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      http_request.setRequestHeader("Content-length", parameters.length);
      http_request.setRequestHeader("Connection", "close");
      http_request.send(parameters);
   }

   function alertContents() {
      if (http_request.readyState == 4) {
         if (http_request.status == 200) {
            //alert(http_request.responseText);
            result = http_request.responseText;
            document.getElementById('myspan').innerHTML = result;            
         } else {
            alert('There was a problem with the request.');
         }
      }
   }
   
   function get(obj) {
      var poststr = "mytextarea1=" + encodeURI( document.getElementById("mytextarea1").value ) +
                    "&mytextarea2=" + encodeURI( document.getElementById("mytextarea2").value );
      makePOSTRequest('post.php', poststr);
   }
</script>


<form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
<textarea id="mytextarea1">my test
1
2
3
</textarea>
<textarea id="mytextarea2">my test2
4
5
6</textarea>
<br>
<input type="button" name="button" value="Submit" 
   onclick="javascript:get(this.parentNode);">
<input type="submit" name="button" value="Normal Submit Button">
</form>

<br><br>
Server-Response:<br>
<hr>
<span name="myspan" id="myspan"></span>
<hr>

post.php
___FCKpd___2

  POST); ?>

 
<think>好的,我现在需要解决用户在Flask应用中遇到的404和405错误。首先,我得回忆一下常见的导致这些错误的原因。404是“Not Found”,通常是因为请求的URL没有对应的视图函数处理。而405是“Method Not Allowed”,意味着视图函数存在,但不支持请求的HTTP方法,比如用GET访问只允许POST的路由,或者反之。 用户之前提到他们遇到了这两个错误,所以我需要分步骤分析可能的原因。首先,针对404错误,常见的问题可能包括路由定义错误,比如拼写错误,或者没有正确注册路由。例如,可能在定义路由时使用了错误的装饰器,或者URL规则中的动态参数处理不当。比如,如果用户访问的是/user/123,但路由定义的是@app.route('/user/<username>'),而实际处理函数中参数名不匹配,也可能导致问题。 然后是405错误,这通常和HTTP方法有关。例如,视图函数默认只允许GET方法,但如果用户尝试用POST方法提交表单到这个路由,而路由没有明确允许POST,就会触发405。需要检查路由装饰器中是否指定了methods参数,比如@app.route('/login', methods=['GET', 'POST'])。如果漏掉了某个方法,就会导致错误。 接下来,我需要考虑如何验证这些可能性。比如,检查应用的路由列表,可以使用app.url_map来查看所有已注册的路由,确认是否存在预期的路由。另外,检查视图函数是否正确定义了允许的HTTP方法。此外,还要注意是否有多个路由规则冲突,导致较晚定义的路由覆盖了前面的,从而引发404错误。 另外,蓝本(Blueprint)的使用也可能导致路由问题。如果用户使用了蓝本,但没有正确注册到应用实例上,或者蓝本中的路由前缀设置错误,也会导致404。需要确认蓝本的注册过程是否正确,比如url_prefix参数是否正确应用。 静态文件或模板文件缺失也可能导致404,但这种情况通常出现在访问静态资源时,比如图片或CSS文件不存在。不过用户的问题可能更关注于路由和视图函数的问题,所以这部分可能需要稍后提及。 还有可能是URL末尾的斜杠问题。Flask会严格处理URL末尾的斜杠,比如定义的路由是'/about',而用户访问的是'/about/',这时候会触发404,除非使用了strict_slashes=False参数。需要检查路由定义是否考虑了这一点。 对于405错误,另一个常见情况是在表单提交时忘记设置method="post",或者AJAX请求中错误地使用了GET方法,而路由只允许POST。需要检查前端代码中的表单或请求方法是否与后端路由匹配。 此外,重定向也可能导致意外的方法问题。例如,某个路由处理POST请求后重定向到一个只允许GET的路由,这时候如果中间有错误的重定向,可能会引发方法不允许的问题。 现在需要将这些可能性整理成解决方案,分步骤指导用户检查。首先是检查路由是否正确,包括拼写、动态参数、方法允许列表。然后检查是否有路由冲突,比如重复定义或蓝本注册问题。接着查看是否有未处理的斜杠问题,以及前端请求方法是否匹配。最后,建议使用调试工具或日志来捕获具体的请求信息,帮助定位问题。 同时,用户可能需要具体的代码示例来对照自己的代码进行修改。例如,展示正确的路由定义,如何处理动态参数,如何指定methods参数等。此外,提醒用户在排查过程中逐步测试,比如注释掉部分代码,确认是否解决了问题,或者使用Flask的调试模式查看详细错误信息。 最后,生成的相关问题需要围绕常见的Flask错误展开,比如500错误处理、路由优化、调试技巧等,帮助用户扩展知识,预防其他潜在问题。</think>### Flask中404与405错误的解决方案 #### 一、404错误(Not Found)原因与修复 1. **路由未正确定义** - 检查路由装饰器`@app.route()`中的URL规则是否与请求路径**完全匹配**,包括大小写和特殊符号。 - 示例错误代码: ```python @app.route('/user') # 访问/user/123会404 def profile(): ... ``` - 正确写法(动态参数需声明): ```python @app.route('/user/<int:user_id>') def profile(user_id): ... ``` 2. **蓝本注册问题** - 若使用蓝本(Blueprint),需确保在应用实例上调用`register_blueprint()`且`url_prefix`正确: ```python from auth_bp import auth app.register_blueprint(auth, url_prefix='/auth') # 蓝本路由需以/auth开头 ``` 3. **斜杠严格模式** - Flask默认严格匹配URL末尾斜杠,访问`/page`与`/page/`会被视为不同路由。可通过参数`strict_slashes=False`放宽限制: ```python @app.route('/about', strict_slashes=False) def about(): ... ``` 4. **静态文件缺失** - 若访问`/static/css/style.css`报错,检查文件是否在`static/css`目录下存在[^1]。 --- #### 二、405错误(Method Not Allowed)原因与修复 1. **未声明支持的HTTP方法** - 默认路由仅允许**GET**请求,若处理POST请求需显式声明: ```python @app.route('/login', methods=['GET', 'POST']) # 同时支持GET和POST def login(): if request.method == 'POST': # 处理表单提交 ``` 2. **前端请求方法不匹配** - 检查HTML表单的`method`属性或AJAX请求类型: ```html <!-- 错误示例:表单声明POST但路由仅允许GET --> <form action="/search" method="POST"> <!-- 触发405 --> ``` 3. **重定向导致方法变更** - 使用`redirect()`时,重定向后的请求会变为**GET**方法。若原路由仅允许POST,需调整逻辑: ```python @app.route('/submit', methods=['POST']) def submit(): # 处理数据后重定向到GET路由 return redirect(url_for('result_page')) ``` --- #### 三、调试工具与验证方法 1. **查看所有注册路由** - 在应用中添加路由列表打印: ```python print(app.url_map) # 输出所有已注册路由及允许的方法 ``` 2. **开启调试模式** - 启动时设置`FLASK_DEBUG=1`,浏览器会显示具体错误堆栈: ```bash export FLASK_DEBUG=1 flask run ``` 3. **使用curl测试接口** - 手动发送请求验证路由响应: ```bash curl -X POST http://localhost:5000/api/data ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值