SORU
6 Kasım 2010, CUMARTESİ


Nasıl sunucu uygulamalarına ve Ajax kullanmak için?

Web uygulamaları ve sunucu uygulamalarına çok yeniyim ve şu soru var:

Sunucu uygulaması içinde bir şeyler baskı ve tarayıcı aramak zaman, yeni bir sayfa metin içeren döndürür. Bir şekilde Geçerli sayfayı Ajax kullanarak metin baskı var mı?

CEVAP
6 Kasım 2010, CUMARTESİ


Gerçekten de, kelime "ajax":Asenkron JavaScript ve XML. Ancak, son yıllarda bunu sık sık daha fazlaAsenkron JavaScript ve JSON. Temelde, JS uyumsuz bir HTTP isteği yürütmek ve HTML DOM ağacı yanıt verilere dayanarak update ver.

O zaman güzel bir tedious iş yapmak için işe genelinde tüm tarayıcılar (özellikle Internet Explorer karşı Diğerleri), orada bir sürü kütüphaneler dışarı kolaylaştırır bu tek işlevleri, gibi jQuery, Prototype, Mootools. JQuery en popüler olduğu örnekler aşağıda kullanacağım.

Düz metin olarak örnek String dönen vuruşu

(Not: kodu JSP dosyası bir alt konuyor) beklemez aşağıda: /some.jsp oluşturun

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

Şöyle ki: doGet() bir yöntem ile bir sunucu uygulaması oluştur

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

Göster bu sunucu üzerinde bir URL desen /someservlet /someservlet/* aşağıda (açıkçası, URL model özgür seçim senin, ama Zorundasınız değiştirmek someservlet URL JS kod örnekleri her yerde buna göre):

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

Ya da, hiç bir Sunucu uygulaması 3.0 Uyumlu konteyner henüz (Tomcat 7, Önemli olan 3, JBoss AS 6, vb veya daha yeni), sonra harita web.xml eski moda yolu (Ayrıca bakınız our Servlets wiki page):

<servlet>
    <servlet-name>someservlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someservlet</servlet-name>
    <url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>

Şimdi tarayıcıda http://localhost:8080/context/test.jsp açın ve düğmesine basın. Div içeriğini sunucu yanıtı ile güncel olsun göreceksiniz.

List<String> JSON olarak dönen

JSON yerine tepki biçimi olarak düz metin ile bile bazı adımlar daha fazla alabilirsiniz. Daha dynamics için izin verir. İlk olarak, bir araç Java nesneleri JSON dizeleri arasında dönüştürmek istersiniz. Onları da (genel bir bakış için this page altına bakın) var. Benim favorim Google Gson. İndir ve KAVANOZUN sizin webapplication /WEB-INF/lib klasöre koyun.

İşte <ul><li> List<String> gösteren bir örnek. Sunucu:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

JS kodu:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

JQuery otomatik olarak JSON olarak yanıt ayrıştırmak ve doğrudan verir unutmayınapplication/json yanıt içerik türü ayarladığınızda bağımsız değişken işlev olarak bir JSON nesnesi (responseJson). Size veya text/plain text/html varsayılan güvenmek unutursan o zaman responseJson bağımsız değişken JSON bir nesne, ama düz vanilya bir dize vermedi.

Map<String, String> JSON olarak dönen

İşte <option> Map<String, String> gösteren başka bir örnek:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<String, String>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

Ve JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

ile

<select id="someselect"></select>

List<Entity> JSON olarak dönen

İşte Product sınıf özellikleri vardır <table> List<Product> gösteren son örnek Long id, String name BigDecimal price. Sunucu:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

JS kodu:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

Varolan bir formu Ajaxifying

Bir WordPress kullanmak $.serialize() kolayca mevcut YAZI formları ajaxify etrafında ve bireysel form giriş parametreleri toplama geçirilmesi ile işe yaramaz olmadan kullanabilirsiniz. JavaScript/jQuery olmadan gayet iyi çalışıyor varolan bir form varsayarsak:

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

Bunu aşağıdaki gibi ajaxify

$(document).on("submit", "#someform", function() {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(responseJson) {
        // ...
    });
});

Uygulamasında aşağıdaki gibi normal istekleri ve ajax istekleri arasında seçim yapabilirsiniz:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON) response.
    } else {
        // Handle regular (JSP) response.
    }
}

jQuery Form plugin daha az ya da daha yukarıda bir WordPress kullanmak örnek olarak aynı işi yapar, ama dosya yükleme gereği multipart/form-data formları için ek şeffaf destek.

Ayrıca Bkz:

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Le Cargo !

    Le Cargo !

    24 HAZİRAN 2007
  • TokShogun

    TokShogun

    6 HAZİRAN 2009
  • wwjoshdew

    wwjoshdew

    1 AĞUSTOS 2007