gpt4 book ai didi

javascript - 使用ajax从http get请求返回html

转载 作者:行者123 更新时间:2023-11-28 03:28:25 27 4
gpt4 key购买 nike

我有点新手,我一直在浏览许多 stackoverflow 页面以找到我正在寻找的答案,但没有成功。

我想做的是:

页面上只有一个文本框和一个按钮

输入一个单词,按下按钮

搜索结果以花哨的方式显示在页面上

简单吧?

我有一个 html 表单提交部分:

<form id="searchHashtag" action="http://localhost:5000/search" method="get">
<label for="hashtag">Search for a hashtag:</label>
<input type="text" name="hashtag" />
<input type="submit" value="send"/>

然后是一个javascript函数:

 <script type="text/javascript" >

<!-- submit action -->
var resp;
jQuery(document).ready(function()
{
$("#searchHashtag").submit( function(event)
{
console.log("event");
event.preventDefault();

/* get some values from elements on the page: */
$.ajax({
url : $(this).attr('action'),
type :$(this).attr('method'),
data :$(this).serialize(),

success :function(response){
$("#contactResponse").show();
resp = response;
},
error:function(xhr, status, errorThrown){
console.log("xhr " + xhr.status);
console.log("status " + status);
console.log("error " + errorThrown);
}
});
return false;
});
});

</script>

我的 CSS 有:

#contactResponse {
height: 600px;
width: 750px;
display: none;
}

响应的 Html 字段:

<div class="contentMain">
<h1>Search results</h1>

<div id="contactResponse">
**Display search results(resp) in a fancy way**
</div>

</div>

现在问题来了,按下按钮搜索消失了:

`http://localhost:5000/search?hashtag=**requestedWord**`

搜索头接收请求没问题它的返回值目前被硬编码为:

<html>OK</html>

http 响应返回 200 并立即重定向到一个页面:

http://localhost:5000/search?hashtag=**requestedWord**

然后在页面上显示“OK”。我尝试将搜索头的返回更改为字符串:

"OK"

甚至转json

({'id:'OK'})

但一切都只是重定向到显示“OK”的页面

我认为 success :function(response){ 应该捕获响应然后允许我使用它。

我做错了什么?请帮助我没有足够的头发来撕掉它......

感谢期待:)

最佳答案

您的代码对我来说没问题。您在提交事件上正确调用了 preventDefault。但是,您需要确保您的 html 标记是正确的。即是否有结束形式标签?

如果您的表单 html 无效,jQuery 将无法找到您的表单(或至少附加到提交事件),但浏览器仍然可以工作并发布表单,因此会重新加载您的页面。

关于javascript - 使用ajax从http get请求返回html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19542218/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com