看了多篇文章,除去那些自己不小心,没加value啥的。自己总结一下。

<body>
		姓名:<input type="text" id="name" />
		年龄:<input type="text" id="age"/>
		<input type="button" value="提交" id="but" />
		<script>
			var name = document.getElementById('name')
			var age = document.getElementById('age')
			var but = document.getElementById('but')
			
			but.onclick = function(){
				const xhr = new XMLHttpRequest()
				var namevalue = name.value
				var agevalue = age.value
				alert(name)
				console.log(name)
				var parm = 'name='+ namevalue +'&age='+agevalue
				
				
				 xhr.open('get', 'http://127.0.0.1:3000/get?'+parm)
				 xhr.send()
				xhr.onload = function (){	
					console.log(xhr.responseText)
			    }
			}
		</script>
	</body>

 

修改前结果:

以上浏览器并无报错,但获取的name元素的值,一直都是[object HTMLInputElement],无法得到value值。

通过查找发现,原来是因为所设参数与HTML内置参数相同,造成在传递过程中,自动转成HTML参数进行传递。

解决办法便是避开。

<body>
		姓名:<input type="text" id="username" />
		年龄:<input type="text" id="age"/>
		<input type="button" value="提交" id="but" />
		<script>
			var username = document.getElementById('username')
			var age = document.getElementById('age')
			var but = document.getElementById('but')
			
			but.onclick = function(){
				const xhr = new XMLHttpRequest()
				var namevalue = username.value
				var agevalue = age.value
				alert(username)
				console.log(username)
				var parm = 'name='+ namevalue +'&age='+agevalue
				
				
				 xhr.open('get', 'http://127.0.0.1:3000/get?'+parm)
				 xhr.send()
				xhr.onload = function (){	
					console.log(xhr.responseText)
			    }
			}
		</script>
	</body>

 

修改后结果:

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐