如何转换jquery's$.post()转换为纯javascript

How to convert jquery's $.post() to plain javascript?

本文关键字:转换 post javascript 何转换 jquery      更新时间:2023-09-26

如何将jquery代码转换为纯JavaScript(即删除jquery依赖项)?

app.html<head>内部

<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
   var textToSend = "blah blah";
   var moreText = "yada yada yada";
   $.post( "process.php", { text1: textToSend, text2: moreText},
      function( data ) {
         alert("Process.php script replies : " + data);
      }
   );
</script>

process.php位于服务器上的同一文件夹中。

<?php
   print "<p>You said " . $_POST['text1'] . "</p>";
   print "<p>Then you added " . $_POST['text2'] . "</p>";
?>

请原谅我的新手含糊其辞。提前谢谢。

直接使用XHR。请注意,jQuery和其他AJAX库抽象掉了寻找合适对象来执行请求的任务。

试试这个。

<script type="text/javascript">
function doPost()
{
    var textToSend = "blah blah";
   var moreText = "yada yada yada";
    var xmlhttp;
    if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
    else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
    xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
     alert("Process.php script replies : " + xmlhttp.responseText);
    }
  }
xmlhttp.open("POST","process.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("text1=" + encodeURIComponent(textToSend) + "&text2=" + encodeURIComponent(moreText) );
}
</script>

编辑:我添加了encodeURIComponent()函数来对参数进行编码。

不用$.post,而是这样做:

var http = new XMLHttpRequest();
var params = "textToSend=" + encodeURIComponent(textToSend) + "&moreText=" + encodeURIComponent(moreText);
http.open("POST", "process.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.onreadystatechange = function() { alert("Process.php script replies : " + http.responseText); };
http.send(params);