2016-04-03 13 views
1

JavaScript işlevinin bir isteğine yanıt olarak bazı HTML göndermek için bir Java Servlet almaya çalışıyorum. Ancak, sunucu işlevi çağrılırken ve bir yanıt gönderirken, Javascript işlevleri boş bir String'den başka bir şey elde etmiyor.Java sunucu yanıtı JavaScript'e bildirme

İşte
String type = request.getParameter("type"); 
if(type.equals("locos")) { 
      response.setContentType("text/html"); 

      //this prints out 
      System.out.println("Responding with vehicle list"); 

      //deal with response 
      PrintWriter out = response.getWriter(); 
      out.write("<p>test response</p>"); //finish 
     } 

JavaScript fonksiyonudur:

this.updateVehicleList = function() { 
     var type = "locos"; 

     var xhr = new XMLHttpRequest(); 
     xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),true); 
     xhr.send(null); 

     //deal with response 
     var res = xhr.responseText; 

     //for testing 
     if (res == "") { 
      window.alert("I'm getting nothing"); 
     } 

     view.showVehicleList(res); 
    }; 

"Hiçbir şey alıyorum" mesajı her zaman verir Burada

Servlet yöntemidir. Servlet'ten yanıt almak için JavaScript’i nasıl alabilirim?

+0

İlgili: [? Servlet ve Ajax nasıl kullanılır] (http://stackoverflow.com/questions/4112686/how-to-use-servlets-and-ajax) çalıştı – BalusC

cevap

1

Zaman uyumsuz bir istekte bulunuluyor ve yanıt hemen alınamıyor. Yanıt alınmadan önce responseText'u almaya çalışıyorsunuz.

onreadystatechange olayı kullanın: Bir senkron istek yapmak niyetinde ise

... 
... 
xhr.send(null); 

xhr.onreadystatechange = function() { 
    if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200){ 
     //deal with response 
     var res = xhr.responseText; 

     //for testing 
     if (res == "") { 
      window.alert("I'm getting nothing"); 
     } 

     view.showVehicleList(res); 
    } 
}; 

ardından false üçüncü argüman ayarlamak ve orijinal kod çalışacaktır.

xhr.open('GET', 'GetList?type=' + encodeURIComponent(type),false); 
//               ^^^^^ 
+0

. Teşekkürler. – Cailean