现有html1和html2,如何在html1中获取html2中表单form的数据
时间: 2024-01-05 15:43:15 浏览: 24
可以通过JavaScript的XMLHttpRequest对象发送POST请求,将html2中form表单的数据发送到服务器,然后在html1中通过XMLHttpRequest的回调函数获取服务器返回的数据。以下是示例代码:
```
var xhr = new XMLHttpRequest();
xhr.open('POST', 'url/to/html2', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var data = xhr.responseText;
// 在这里处理服务器返回的数据
}
};
var formData = new FormData(document.getElementById('form-id-in-html2'));
xhr.send(formData);
```
其中formData就是html2中form表单的数据。注意,由于涉及到跨域请求,如果html1和html2不在同一个域名下,需要在服务器端设置CORS。