Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...