2014-01-06 79 views
1

我想要像下面那樣使用Jquery .ajax方法來訪問一個servlet。Ajax從Jquery調用servlet

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

Servlet的內容:

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

    } 

每次我打電話此.ajax功能被擊中的servlet,使呼叫.ajax error:function(){}

爲什麼不撥打.ajax success:function(){}

+0

您的MacawServlet映射到什麼網址? –

回答

1

你的js和java文件是否在相同的上下文中?

如果是,則不需要在url中使用服務器地址和端口。您可以從/ Macaw/MacawServlet開始

如果不是,請選中啓用跨瀏覽器ajax調用。

請參閱 - Firefox setting to enable cross domain ajax request