为什么我的AJAX数据加载然后消失了? [英] Why does my AJAX data load then disappear?

查看:66
本文介绍了为什么我的AJAX数据加载然后消失了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从电影数据库API加载JSON数据.AJAX在搜索功能中加载,可以正常工作,但随后消失.这是代码:

I am loading JSON data from a movie database API. The AJAX loads within a search function, it works fine but then disappears. Here's the code:

<div class="form-group">
    <label for="movie">inserisci film:</label>
    <input type="text" class="form-control" id="movie" type="text"></input>
</div>
<button type="submit" onclick="search()" class="btn btn-default">cerca</button>

然后我调用该函数

function search() {
    var film = document.getElementById('movie').value;
    var key = '?api_key=somekey';
    alert(film + key);
    $.ajax({    
        type: 'GET',
        url : 'http://api.themoviedb.org/3/search/movie'+key+'&query='+film,
        async: false,
        data: {
            format: 'json'
        },
        success: function(data){
            $('#titolo').append(data.results[0].original_title);
            $('#immagine').append('<img src=' + url + key +  ata.results[0].poster_path + '></img>');
            console.log(data);
        },              
    });
};

有什么问题吗?谢谢

推荐答案

  1. 您单击提交按钮
  2. JavaScript运行
  3. ajax请求已发送
  4. 因为 async:false ,整个UI都将锁定,直到完成JS
  5. 通过成功函数更新DOM
  6. 表单提交
  7. 浏览器加载新页面
  1. You click the submit button
  2. The JavaScript runs
  3. The ajax request is sent
  4. Because async: false the entire UI locks up until the JS is done
  5. The DOM is updated by the success function
  6. The form submits
  7. The browser loads a new page

如果要使用内在事件属性(不应使用),则需要从函数中 return false 来停止事件的正常发生.

If you are going to use intrinsic event attributes (which you shouldn't), then you need to return false from the function to stop the normal behaviour of the event from occurring.

onclick="search(); return false;"

这篇关于为什么我的AJAX数据加载然后消失了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆