简体   繁体   中英

Ajax call to servlet from Jquery

I'm trying to access a servlet using Jquery .ajax method like below.

function ajaxCall()
    {
     $.ajax({
        type: 'GET',
        dataType:"html",
        url: "http://localhost:7001/Macaw/MacawServlet",
        success:function(data){
         alert(data);
        },
    error:function(){
         alert("failure");
        }                   
    });
    }

Servlet Content:

   package servlet;

   import java.io.File;
   import java.io.IOException;
   import java.io.PrintWriter;

   import javax.servlet.ServletConfig;
   import javax.servlet.ServletException;
   import javax.servlet.http.HttpServlet;
   import javax.servlet.http.HttpServletRequest;
   import javax.servlet.http.HttpServletResponse;

   import org.jsoup.Jsoup;
   import org.jsoup.nodes.Document;
   import org.jsoup.nodes.Element;


   public class MacawServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

       public MacawServlet() {
           super();
           // TODO Auto-generated constructor stub
       }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        File input = new File("C:/Users/540893/workspace/Macaw/WebContent/prpsl_txtsrch.html");
        Document doc = Jsoup.parse(input,"UTF-8");
        Element content = doc.getElementById("text_search");
        Element content1 = doc.getElementById("chr_val_stats");
        Element content2 = doc.getElementById("chr_val_delta");
        out.println(content);
        out.println(content1);
        out.println(content2);
        System.out.println("success");
    }

   }

Everytime i'm calling this .ajax function it is hitting the servlet and making call to .ajax error:function(){} .

Why it is not calling the .ajax success:function(){} ?

Is your js and java file in same context?

If yes, no need to use server address and port in url. You can start with /Macaw/MacawServlet

If not, check to enable cross browser ajax call.

Refer - Firefox setting to enable cross domain ajax request

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM