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

标签 javascript html css ajax

我有点新手,我一直在浏览许多 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/

相关文章:

javascript - React Native 布局动画不是动画?还是做错了?

javascript - 如何使用 javascript 创建自定义关键帧 css 动画

css - 将不同大小的图像适合特定格式

html - 在断点处更改 Bootstrap 3 全局字体大小

javascript - 文本输入的 "value"属性不正确

javascript - jQuery 进行选择

javascript - IsNullOrEmpty 属性

html - CSS 简单菜单 - 如何对齐?

php - 使用 php 突出显示菜单

html - Bootstrap 3 : Content in a new row is not aligned