当事件从“ mouseover”更改时,脚本无效点击“单击”
当我将事件更改为“单击”而不是“鼠标”时,以下脚本无效。知道为什么吗? 我的意思是不起作用的是,我无法将任何JSON数据发布到JSON存储服务。
<script>
const button = document.getElementById("search-image")
const s = document.getElementById("s")
function SendData(){
var xhr = new XMLHttpRequest();
var url = "https://krat.es/xxxxx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
}
};
var data = JSON.stringify({"Text": s.value});
console.log(data)
xhr.send(data);
}
button.addEventListener("mouseover",SendData)
</script>
更新:HTML代码
<form _lpchecked="1" action="/search" class="search-form" id="searchform" method="get">
<fieldset>
<input id="s" name="q" onfocus="if(this.value=='Search')this.value='';" onwebkitspeechchange="transcribe(this.value)" type="text" value="Search" x-webkit-speech="">
<button class="sbutton" id="search-image" style="border:0; vertical-align: top;background: transparent;"><i class="fa fa-search"></i></button>
</fieldset>
</form>
The following script doesn't work when I change the event to "click" instead of "mouseover". Any idea why?
What I mean by doesn't work is, that I cant POST any JSON data to the JSON storage service.
<script>
const button = document.getElementById("search-image")
const s = document.getElementById("s")
function SendData(){
var xhr = new XMLHttpRequest();
var url = "https://krat.es/xxxxx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
}
};
var data = JSON.stringify({"Text": s.value});
console.log(data)
xhr.send(data);
}
button.addEventListener("mouseover",SendData)
</script>
Update: HTML code
<form _lpchecked="1" action="/search" class="search-form" id="searchform" method="get">
<fieldset>
<input id="s" name="q" onfocus="if(this.value=='Search')this.value='';" onwebkitspeechchange="transcribe(this.value)" type="text" value="Search" x-webkit-speech="">
<button class="sbutton" id="search-image" style="border:0; vertical-align: top;background: transparent;"><i class="fa fa-search"></i></button>
</fieldset>
</form>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的按钮在表格内。因此,当您单击“表单”按钮时,它将发送,并且不允许您的JavaScript代码运行。
因此,以这种方式更改按钮代码
HTML:
JS:
Your button is inside a form. So when you click the form button, it will be sent and will not allow your JavaScript code to run.
So change the button code this way
html :
js :
您可以通过单击替换鼠标,并且需要在搜索区域输入文本并输入您将能够获得响应
请参阅下面的链接以获取完整代码
You can replace mouseover with click and you need to type the text on search area and enter you will be able to get the response
please refer below link for full code