如何使用ajax和javascript显示有关鼠标悬停的其他信息

时间:2017-05-20 00:45:42

标签: javascript jquery ajax jsp

我有一个用于购买电影的电子商务模拟网络应用程序,当用户将鼠标悬停在电影的ID上并显示信息并让他们选择将该电影添加到购物车时,我想要一个弹出小窗口(如当您将一个朋友的名字移到鼠标上时,Facebook会显示用户信息。我有一个java servlet接收电影的id并从我的数据库中获取正确的信息并将其发送回JSP,但在那里形成我不知道如何正确使用AJAX或jquery来显示具有正确信息的窗口。

服务代码

int movie_id = Integer.parseInt((String) request.getParameter("movie_id"));
    StringBuilder query = new StringBuilder("select * from movies where movies.id =");
    query.append(movie_id);

    // Perform the query
    MySQLHandler sql_handler = new MySQLHandler( );
    sql_handler.execute_query( query.toString() );
    ResultSet result = sql_handler.get_result();


    try {
        Movie movie = createMovie(result);

        response.setContentType("text/html");

        PrintWriter out = response.getWriter();
        out.println(movie.getTitle());
        request.setAttribute("movie", movie);
    } 
    catch(SQLException e) {
        e.printStackTrace();
    }
}

JAVASCRIPT CODE

function ajaxFunction(movie_id){
var ajaxRequest;  // The variable that makes Ajax possible!

try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
} catch (e){
    // Internet Explorer Browsers
    try{
        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
            // Something went wrong
            alert("Your browser broke!");
            return false;
        }
    }
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
    if(ajaxRequest.readyState == 4){
        alert(ajaxRequest.responseText);
    }
}
alert(movie_id);
var parameter = "movie_id=" + movie_id;
ajaxRequest.open("POST","MoviePopUpWindowServlet", true);
ajaxRequest.setRequestHeader("Content-type"
        , "application/x-www-form-urlencoded") //Needed for post request for some reason. //http://www.javascriptkit.com/dhtmltutors/ajaxgetpost2.shtml
ajaxRequest.send(parameter);

}

1 个答案:

答案 0 :(得分:0)

            $.ajax({
                url: 'route/to/videoinfo' + specificVideoId,
                type: "POST", 
                contentType: "application/json ;charset=UTF-8", 
            }).done(function(result){
                (if you rendered out the html already just do)
                var containerDiv = document.getElementById("#idOfDivToFill")
                containerDiv.innerHTML = result
            }).fail(function(err){
                console.log(err)
            })

有人告诉我这是不是很糟糕。