<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03.ajax的post的参数传递</title>
</head>
<body>
<h1>03.ajax的post的参数传递</h1>
name:<input type="text" id="name"><br/>
password:<input type="text" id='name'><br/>
<input type="button" value="获取参数" onclick="submitForm()">
<input type="button" value="获取参数-post" onclick="submitForm2()">
<script>
function submitForm(){
var name = document.getElementById('name').value
var pwd = document.getElementById('pwd').value
url='http://httpbin.org/get'
params='name='+name+'&pwd'+pwd
var xhr=new XMLHttpRequest()
xhr,open('post',url)
xhr.setRequestHeader('Content-Type','application/x_wwww-form-urlencoded')
xhr.send(params)
xhr.onload = function(){
console.log(xhr.responseText)
}
}
function submitForm2(){
var name = document.getElementById('name').value
var pwd = document.getElementById('pwd').value
url='http://httpbin.org/post'
params={'name':name,'pwd':pwd}
var xhr=new XMLHttpRequest()
xhr,open('post',url)
xhr.setRequestHeader('Content-Type','application/json')
xhr.send(params)
xhr.onload = function(){
console.log(xhr.responseText)
}
}
</script>
</body>
</html>
报错原因:
03.Ajax的post的参数传递.html:31 Uncaught TypeError: Cannot read properties of null (reading 'value')
at submitForm2 (03.Ajax的post的参数传递.html:31)
at HTMLInputElement.onclick (03.Ajax的post的参数传递.html:12)
submitForm2 @ 03.Ajax的post的参数传递.html:31
onclick @ 03.Ajax的post的参数传递.html:12