AJAX表单POST请求-HTML表单POST/Submit with AJAX/Javascript示例/教程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX表单POST请求-HTML表单POST/Submit with AJAX/Javascript示例/教程相关的知识,希望对你有一定的参考价值。

  1. post.html:
  2.  
  3. <script type="text/javascript" language="javascript">
  4. var http_request = false;
  5. function makePOSTRequest(url, parameters) {
  6. http_request = false;
  7. if (window.XMLHttpRequest) { // Mozilla, Safari,...
  8. http_request = new XMLHttpRequest();
  9. if (http_request.overrideMimeType) {
  10. // set type accordingly to anticipated content type
  11. //http_request.overrideMimeType('text/xml');
  12. http_request.overrideMimeType('text/html');
  13. }
  14. } else if (window.ActiveXObject) { // IE
  15. try {
  16. http_request = new ActiveXObject("Msxml2.XMLHTTP");
  17. } catch (e) {
  18. try {
  19. http_request = new ActiveXObject("Microsoft.XMLHTTP");
  20. } catch (e) {}
  21. }
  22. }
  23. if (!http_request) {
  24. alert('Cannot create XMLHTTP instance');
  25. return false;
  26. }
  27.  
  28. http_request.onreadystatechange = alertContents;
  29. http_request.open('POST', url, true);
  30. http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  31. http_request.setRequestHeader("Content-length", parameters.length);
  32. http_request.setRequestHeader("Connection", "close");
  33. http_request.send(parameters);
  34. }
  35.  
  36. function alertContents() {
  37. if (http_request.readyState == 4) {
  38. if (http_request.status == 200) {
  39. //alert(http_request.responseText);
  40. result = http_request.responseText;
  41. document.getElementById('myspan').innerHTML = result;
  42. } else {
  43. alert('There was a problem with the request.');
  44. }
  45. }
  46. }
  47.  
  48. function get(obj) {
  49. var poststr = "mytextarea1=" + encodeURI( document.getElementById("mytextarea1").value ) +
  50. "&mytextarea2=" + encodeURI( document.getElementById("mytextarea2").value );
  51. makePOSTRequest('post.php', poststr);
  52. }
  53. </script>
  54.  
  55.  
  56. <form action="javascript:get(document.getElementById('myform'));" name="myform" id="myform">
  57. <textarea id="mytextarea1">my test
  58. 1
  59. 2
  60. 3

以上是关于AJAX表单POST请求-HTML表单POST/Submit with AJAX/Javascript示例/教程的主要内容,如果未能解决你的问题,请参考以下文章

解决YII提交POST表单出现400错误,以及ajax post请求时出现400问题

通过html表单方式提交数据(可以指定get和post)和ajax方式请求的原理是一样的吗?

HTML中ajax表单提交CSRF保护

表单在 2 次 ajax 更新后无法发送 POST 请求

form表单的post请求和ajax的post的请求都有哪些区别

使用 jQuery AJAX 向所需的 PHP POST 请求处理程序提交表单不起作用