繁体   English   中英

如何将jquery的$ .post()转换为纯JavaScript?

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

您如何将这个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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM