如何将此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>";
?>
原谅我的新手模糊。 提前谢谢。
答案 0 :(得分:3)
直接使用XHR。请注意,jQuery和其他AJAX库抽象出finding an appropriate object的任务来执行请求。
答案 1 :(得分:2)
试试这个。
<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()
函数来编码参数。
答案 2 :(得分:2)
而不是$ .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);