Example of Using ajax to submit POST data and ajax to submit post Data
Problem description
We asynchronously submit the data in the input and checkbox of a form to the php server. After processing, the data is returned.
Position displayed after submission:
Difficulties
Use the onsubmit attribute of the from form to block form submission.
<form action="http://www.baidu.com" onsubmit="return check()">
Use the return false function of the check function to prevent form submission, so that the data is not refreshed and submitted.
Obtain the value of the option selected by the check box.
Checkbox label section:
<Input type = "checkbox" name = "checkbox" id = "multi-choiceA" value = "A"> Option A <br/> <input type = "checkbox" name = "checkbox" id = "multi-choiceB" value = "B"> Option B <br/> <input type = "checkbox" name = "checkbox" id = "multi-choiceC "value =" C "> Option C <br/> <input type =" checkbox "name =" checkbox "id =" multi-choiceD "value =" D "> Option D <br/>
Javascript processing:
Var str = document. getElementsByName ("checkbox"); var answer = ""; for (var I = 0; I <str. length; I ++) {if (str [I]. checked = true) {answer + = str [I]. value ;}} if (answer = "") alert ('Check the answer and submit'); else {// The user selects the relevant answer to process var xmlhttp;
Use ajax technology to interact with the background
var xmlhttp;xmlhttp = new XMLHttpRequest();xmlhttp.open("POST","function.php",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("qid="+qid+"&answer="+answer);xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } };
Region Code frontend index.html
<! Doctype html>
Backend function. php
<! Doctype html>
Effect display: