index.html:21 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
at HTMLInputElement.document.querySelector.onclick (http://127.0.0.1:8081/chattest/index.html:21:13)
百度和谷歌查了个遍还是不知道怎么解决。
源代码:
<h3>ajax请求</h3>
<input type="button" value="ajax请求返回xml">
document.querySelector('input').onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open = ('post' , 'backxml.php');
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
console.log(xhr.responseText);
}
}
xhr.send(null);
}
```').
```php
$xmlString = file_get_contents('person.xml');
echo $xmlString;
照着B站AJAX教程打的代码,跟那个一模一样,但是我的就是运行不了,检查了十几二十遍。TAT
=号去掉,要调用xhr对象的oen方法后才能send
建议onreadystatechange该这样,要不服务器端有问题就会和没反应一样,只能开浏览器调试工具看网络请求
<h3>ajax请求</h3>
<input type="button" value="ajax请求返回xml">
<script>
document.querySelector('input').onclick = function () {
var xhr = new XMLHttpRequest();
xhr.open ('post', 'backxml.php');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
} else
alert('服务器有问题\n' + xhr.responseText)
}
}
xhr.send(null);
}
</script>
这个好像不是代码的问题,跨域了
这是请求跨域问题,如果可以让后端去添加白名单,如果不行前端自己解决跨域的方式也有很多 https://segmentfault.com/a/1190000011145364