Why can't my code pass parameters from JavaScript to JSP using XMLHttpRequest?

I am trying to write JavaScript code that sends a parameter (id) to server-side JSP code when a mouse event occurs. Then the JSP code returns a JavaScript string.

... and the response text will be the string returned from the JSP specified in out.println(substring);.

This code does not work. Sorry if I do something stupid; I am new to coding for the web.

+3
source share
3 answers

XMLHttpRequest - , send . , , , . :

xmlHttp.onreadystatechange = handleRequestStateChange

, handleRequestStateChange. , onreadystatechange.

:

<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
    // Declare the variables we'll be using
    var xmlHttp, handleRequestStateChange;

    // Define the function to be called when our AJAX request state changes:
    handleRequestStateChange = function()
    {
        // Check to see if this state change was "request complete", and
        // there was no server error (404 Not Found, 500 Server Error, etc)
        if (xmlhttp.readyState==4 && xmlhttp.status==200) 
        {
            var substring=xmlHttp.responseText;
            // Do something with the text here
            alert(substring);
        }
    }

    xmlhttp = new XMLHttpRequest();
    xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
    xmlHttp.onreadystatechange = handleRequestStateChange;
    xmlHttp.send(null);
}
</script>

handleRequestStateChange , XMLHttpRequest. , 4 ( , ), , responseText , JSP.

, , AJAX, , ​​ jQuery. , !

+7

( GET) open ( URL)

xhr.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xhr.send(null);

Goyuix POST:

xhr.open("POST", "http://csce:8080/test/index.jsp", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("id=c6c684d9cc99476a7e7e853d77540ceb");

, uri encoding global , :

POST:

var myVar1 = encodeURIComponent("c6c684d9cc99476a7e7e853d77540ceb");
xhr.open("POST", "http://csce:8080/test/index.jsp", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("id=" + myVar1);

GET:

var myVar1 = encodeURIComponent("c6c684d9cc99476a7e7e853d77540ceb");
xhr.open("GET", "http://csce:8080/test/index.jsp?id=" + myVar1, true);

FYI, , JSP:

JSP ( -/WEB-INF/lib/directory), "id".

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:out value="${param.id}"/>
+2

Instead of the null method in the send method, try passing something like "key = value" that should appear in your JSP request object, and you can access it by calling something like:

string myValue = request.getParameter("key");
+1
source

Source: https://habr.com/ru/post/1769818/


All Articles