Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
214 views
in Technique[技术] by (71.8m points)

javascript - Why does my AJAX data load then disappear?

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>

Then I call the function

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);
        },              
    });
};

there is something wrong? thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  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

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;"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...