How is it right to send Ajax request to web services?



  •  $("#submit").on('click',function () {
    

    $.ajax({

    url:"http://localhost:8080/webtest/service",
    method:"POST",
    dataType:"application/json",
    success:function () {
        alert("Ajax request success");
    },
    error:function () {
        alert("look at the response headers for error!")
    }
    

    });

    });

    });

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Tests</title>

    &lt;script src="jquery-3.1.0.js"&gt;&lt;/script&gt;
    &lt;script src = "https://code.jquery.com/jquery-1.11.3.js"&gt;&lt;/script&gt;
    &lt;script src = "https://code.jquery.com/jquery-2.1.4.js"&gt;&lt;/script&gt;
    

    </head>
    <body>

    <form">

    &lt;label for = "username"&gt;UserName:&lt;/label&gt;
    &lt;input id = "username"&gt;&lt;br&gt;
    &lt;label for = "email"&gt;Email:&lt;/label&gt;
    &lt;input id = "email" type="email"&gt;&lt;br&gt;
    &lt;label for = "password"&gt;Password:&lt;/label&gt;
    &lt;input id = "password" type="password"&gt;&lt;br&gt;
    &lt;input id = "submit" type="button" value="Send!"&gt;
    

    </form>

    <script src="requests.js"></script>
    </body>
    </html>

    @WebServlet(name = "webService" , urlPatterns = "/service")
    public class WebServiceDemo extends HttpServlet {

        response.setHeader("Access-Control-Allow-Origin","*");
        response.getWriter().print("In the if else DO POST METHOD");
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    **//When the server starts i got response from here!**
    response.getWriter().print("Hello from servlet");
    
    }
    

    }

    I'll meet Ajax requests. What's wrong with this code? In an attempt to pass the request, the error report. I'll get back from the server 200! But Jquery Ajax's code for error with the alerator! Why?

    введите сюда описание изображения



  • I've just learned the question and I'm doing it:

    function loadDoc()
                {
                    xmlhttp = new XMLHttpRequest();
                    xmlhttp.onreadystatechange = function ()
                    {
                        if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
                        {
                            processJSON(xmlhttp.responseText);
                        }
                    }
    
                var url = 'your url';
    
                xmlhttp.open("GET", url, true);
                xmlhttp.send();
            }
    
            function processJSON(json) {
    
                if (typeof JSON !== "undefined") {
                    json = JSON.parse(json);
                  
                  //your code
                  
                }
            }</code></pre></div></div></p>



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2