簡體   English   中英

獲取ajax發布請求的用戶輸入?

[英]Getting user input for ajax post request?

我正在通過以下網址瀏覽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>

上面的示例存在的問題是fnamelname的值是硬編碼的。 如何允許用戶通過<form>標簽為fnamelname輸入不同的值,並且仍然能夠使用Ajax JavaScript代碼?

為此創建了jsfiddle示例:-http: //jsfiddle.net/c2S5d/24/

為fname和lname添加了兩個輸入,並在其中獲取了值並設置為參數。(到目前為止,已經注釋了ajax send的代碼)嘗試在給定的鏈接上方輸入一些值,並在文本框中輸入一些值,然后查看警告)代碼:-

<!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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM