我正在阅读Ajax教程: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
他们有这个例子来向服务器提交请求:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
我对上述示例的问题是fname
和lname
的值是硬编码的。如何允许用户通过fname
代码为lname
和<form>
输入不同的值,并且仍然可以使用ajax javascript代码?
答案 0 :(得分:2)
创建了同样的jsfiddle示例: - http://jsfiddle.net/c2S5d/24/
为fname和lname添加了两个输入并获取了值并设置为params。(截至现在评论了ajax发送的代码)尝试上面给出的链接并在框中输入一些值并查看警报) 代码: -
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
alert("calle")
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) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value
//xmlhttp.open("POST","demo_post2.asp",true);
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var param = "fname=" + fname + "&lname=" + lname;
alert(param)
//xmlhttp.send(param);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
<input type='text' id='fname' />
<input type='text' id='lname' />
</body>
</html>