从 servlet 更改元素的值并将数据返回到网页而不使用 ajax 刷新

Posted

技术标签:

【中文标题】从 servlet 更改元素的值并将数据返回到网页而不使用 ajax 刷新【英文标题】:Change an element's value from servlet and return data to webpage without refresh with ajax 【发布时间】:2021-11-02 19:32:21 【问题描述】:

我有一个网页和一个 servlet。我在网页中使用 javascript 动态创建输入元素。 servlet 是评估一些数学计算的后端。我正在从动态创建的输入元素中获取要发送到 servlet 的数据。这些输入元素的 id 也是动态创建的。我能够检索数据并创建元素而不会出现任何错误。

但是,我想评估 servlet 中的一些数学运算,然后将结果发送到网页中的“结果”文本框。所以我不想刷新网页。因为“结果”id 文本框也在动态创建。

相关的html代码。

<form action="/TYT_Mat_Soru_Cozumu_Java_war_exploded/Servlet/HesaplamaIslemleri" method="post" id="sayilarForm">
      <input type="hidden" name="grupNoTutan" id="grupNoTutan"></input>
    </form>

动态创建输入元素的代码。

  function sayiEklemeKutular(operatorTipi)
  var satir_1Div = document.createElement("div");
  satir_1Div.setAttribute("class", "row");
  satir_1Div.setAttribute("id", grup_no + "_satir_1");
  var satir_2Div = document.createElement("div");
  satir_2Div.setAttribute("class", "row");
  var satir_3Div = document.createElement("div");
  satir_3Div.setAttribute("class", "row");
  var satir_4Div = document.createElement("div");
  satir_4Div.setAttribute("class", "row");
  var satir_5Div = document.createElement("div");
  satir_5Div.setAttribute("class", "row");

  var node = "";
  switch (operatorTipi) 
    case "+":
      node = document.createTextNode('+');
      break;
    case "-":
      node = document.createTextNode('-');
      break;
    case "*":
      node = document.createTextNode('*');
      break;
    case "/":
      node = document.createTextNode('/');
      break;
    case "√":
      node = document.createTextNode('√');
      break;
    case "0/":
      node = document.createTextNode('0/');
      break;
    case "^√==":
      node = document.createTextNode('^√==');
      break;
    case "^==":
      node = document.createTextNode('^==');
      break;
    default:
      node = document.createTextNode('Hata');
  
  satir_3Div.appendChild(node);
  satir_3Div.style.textAlign = "center";
  satir_3Div.style.fontSize = "14pt";
  satir_3Div.style.fontColor = "#ffffff";

  var satir_2_sutun_1Div = document.createElement("div");
  var satir_2_sutun_2Div = document.createElement("div");
  var satir_2_sutun_3Div = document.createElement("div");
  satir_2_sutun_1Div.setAttribute("class", "col");
  satir_2_sutun_2Div.setAttribute("class", "col");
  satir_2_sutun_3Div.setAttribute("class", "col");

  var satir_4_sutun_1Div = document.createElement("div");
  var satir_4_sutun_2Div = document.createElement("div");
  var satir_4_sutun_3Div = document.createElement("div");
  satir_4_sutun_1Div.setAttribute("class", "col");
  satir_4_sutun_2Div.setAttribute("class", "col");
  satir_4_sutun_3Div.setAttribute("class", "col");

  var satir_5_sutun_1Div = document.createElement("div");
  var satir_5_sutun_2Div = document.createElement("div");
  var satir_5_sutun_3Div = document.createElement("div");
  satir_5_sutun_1Div.setAttribute("class", "col");
  satir_5_sutun_2Div.setAttribute("class", "col");
  satir_5_sutun_3Div.setAttribute("class", "col");

  var kokDerece1 = document.createElement("input");
  var kokKatsayi1 = document.createElement("input");
  var kokIciDeger1 = document.createElement("input");

  kokDerece1.setAttribute("name", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece1.setAttribute("id", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece1.setAttribute("class", "form-control");
  kokDerece1.setAttribute("type", "text");
  kokDerece1.setAttribute("placeholder", "Kökün Derecesi");

  kokIciDeger1.setAttribute("name", grup_no +  "_kokIciDeger_" + komponent_no);
  kokIciDeger1.setAttribute("id", grup_no + "_kokIciDeger_" + komponent_no);
  kokIciDeger1.setAttribute("class", "form-control");
  kokIciDeger1.setAttribute("type", "text");
  kokIciDeger1.setAttribute("placeholder", "Kök İçindeki Değer");

  kokKatsayi1.setAttribute("name", grup_no +  "_kokKatsayi_" + komponent_no);
  kokKatsayi1.setAttribute("id", grup_no + "_kokKatsayi_"+ komponent_no);
  kokKatsayi1.setAttribute("class", "form-control");
  kokKatsayi1.setAttribute("type", "text");
  kokKatsayi1.setAttribute("placeholder", "Kökün Katsayısı");

  komponent_no = komponent_no + 1;

  var kokDerece2 = document.createElement("input");
  var kokIciDeger2 = document.createElement("input");
  var kokKatsayi2 = document.createElement("input");

  kokDerece2.setAttribute("name", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece2.setAttribute("type","text");
  kokDerece2.setAttribute("id", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece2.setAttribute("class", "form-control");
  kokDerece2.setAttribute("placeholder", "Kökün Derecesi");

  kokIciDeger2.setAttribute("name", grup_no +  "_kokIciDeger_" + komponent_no);
  kokIciDeger2.setAttribute("type", "text");
  kokIciDeger2.setAttribute("id", grup_no + "_kokIciDeger_" + komponent_no);
  kokIciDeger2.setAttribute("class", "form-control");
  kokIciDeger2.setAttribute("placeholder", "Kök İçindeki Değer");

  kokKatsayi2.setAttribute("name", grup_no + "_kokKatsayi_" + komponent_no);
  kokKatsayi2.setAttribute("type","text");
  kokKatsayi2.setAttribute("id", grup_no + "_kokKatsayi_"+ komponent_no);
  kokKatsayi2.setAttribute("class", "form-control");
  kokKatsayi2.setAttribute("placeholder", "Kökün Katsayısı");

  var sonucInput = document.createElement("INPUT");
  sonucInput.setAttribute("class", "form-control");
  sonucInput.setAttribute("name", grup_no + "_sonuc");
  sonucInput.setAttribute("id", grup_no + "_sonuc");
  sonucInput.setAttribute("placeholder", "Sonuç");

  var silButon = document.createElement("BUTTON");
  silButon.setAttribute("class", "btn btn-danger");
  silButon.setAttribute("name", grup_no + "_silButon");
  silButon.textContent = "Grubu Sil";
  silButon.setAttribute("onclick", 'silButonununGrupNosunuGetir(this.getAttribute("name"))');


  var hesaplaButon = document.createElement("BUTTON");
  hesaplaButon.setAttribute("class", "btn btn-success");
  hesaplaButon.setAttribute("type", "submit");
  hesaplaButon.setAttribute("name", grup_no + "_hesaplaButon");
  hesaplaButon.setAttribute("onclick", 'ismiHiddenaEkle(this.getAttribute("name"))');
  hesaplaButon.textContent = "Hesapla";

  komponent_no = 1;
  grup_no = grup_no + 1;

  satir_2_sutun_1Div.appendChild(kokDerece1);
  satir_2_sutun_2Div.appendChild(kokKatsayi1);
  satir_2_sutun_3Div.appendChild(kokIciDeger1);

  satir_2Div.appendChild(satir_2_sutun_1Div);
  satir_2Div.appendChild(satir_2_sutun_2Div);
  satir_2Div.appendChild(satir_2_sutun_3Div);

  satir_4_sutun_1Div.appendChild(kokDerece2);
  satir_4_sutun_2Div.appendChild(kokKatsayi2);
  satir_4_sutun_3Div.appendChild(kokIciDeger2);

  satir_4Div.appendChild(satir_4_sutun_1Div);
  satir_4Div.appendChild(satir_4_sutun_2Div);
  satir_4Div.appendChild(satir_4_sutun_3Div);

  satir_5_sutun_1Div.appendChild(sonucInput);
  satir_5_sutun_2Div.appendChild(silButon);
  satir_5_sutun_3Div.appendChild(hesaplaButon);

  satir_5Div.appendChild(satir_5_sutun_1Div);
  satir_5Div.appendChild(satir_5_sutun_2Div);
  satir_5Div.appendChild(satir_5_sutun_3Div);

  satir_1Div.appendChild(satir_2Div);
  satir_1Div.appendChild(satir_3Div);
  satir_1Div.appendChild(satir_4Div);
  satir_1Div.appendChild(satir_5Div);

  satir_1Div.style.marginTop = '30px';
  satir_3Div.style.marginTop = '10px';
  satir_4Div.style.marginTop = '10px';
  satir_5Div.style.marginTop = '10px';

  satir_1Div.style.backgroundColor = "#18A2D9";
  satir_1Div.style.padding = "10px";
  satir_1Div.style.borderRadius = "2em";

  var formId = document.getElementById("sayilarForm");
  formId.appendChild(satir_1Div);


The code that add sequence number of created dynamically element to a hidden element and calling the Ajax code.

    function ismiHiddenaEkle(name)
          var hiddenEleman = document.getElementById("grupNoTutan");
          hiddenEleman.value = name;
          hesaplaServleteGonder();
        
    
    The Javascript code that contain Ajax.
    
        function hesaplaServleteGonder()
        var butonAdi= document.getElementById("grupNoTutan").value;
        var grup_no = butonAdi.charAt(0);
        var i = 1;
    
        var birinciKokDerecesi;
        var birinciKatsayi;
        var birinciKokIciDeger;
    
        var ikinciKokDerecesi;
        var ikinciKatsayi;
        var ikinciKokIciDeger;
        var sonuc;
        birinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
        birinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
        birinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
        sonuc = document.getElementById(grup_no + "_sonuc");
        i= i + 1;
        ikinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
        ikinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
        ikinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
        i = 1;
        $.ajax(
          type:'POST',
          url:'/TYT_Mat_Soru_Cozumu_Java_war_exploded/Servlet/HesaplamaIslemleri',
          dataType: 'json',
          contentType:'application/json',
          data:  $('#sayilarForm').serialize() ,
          cache:false,
          success:function(data)
            alert(data);
            $('#sonuc').text(responseText);
          ,
          error:function()
            alert('error');
          
        );
    

servlet 在下面。

@WebServlet("/Servlet/HesaplamaIslemleri")
public class HesaplamaIslemleri extends HttpServlet 
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 

        PrintWriter out = resp.getWriter();

        StringBuilder sb = new StringBuilder();
        BufferedReader br = req.getReader();
        String str;
        while( (str = br.readLine()) != null )
            sb.append(str);
        
        System.out.println(sb.toString());
        resp.getWriter().print(sb.toString());
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        doPost(req,resp);
    


当我单击按钮时,正在加载一个新页面,并且页面中有带有其名称的值。 像这样 grupNoTutan=1_hesaplaButon&1_kokDerecesi_1=2&1_kokKatsayi_1=4&1_kokIciDeger_1=2&1_kokDerecesi_2=2&1_kokKatsayi_2=8&1_kokIciDeger_2=2&1_sonuc=&1_hesaplaButon=

谁能帮忙?

【问题讨论】:

【参考方案1】:

我用这种方式解决了这个问题。 Servlet 和 javascript 代码如下。首先,我将json数据分解成碎片来理解结构。然后,我根据哪个部分是数组,哪个部分是对象来处理数据。 (动态创建的元素序列号存储在名为('grupNoTutan')的隐藏元素中

Javascript:

  //Read the content of elements that created dynamically
  var butonAdi= document.getElementById("grupNoTutan").value;
  var grup_no = butonAdi.charAt(0);
  var i = 1;

  var birinciKokDerecesi;
  var birinciKatsayi;
  var birinciKokIciDeger;

  var ikinciKokDerecesi;
  var ikinciKatsayi;
  var ikinciKokIciDeger;
  var sonuc;
  var operator = document.getElementById("operator").textContent;
  //var url = "#" +  grup_no + "_kokDerecesi_" + i
  //var textboxvalue = $("'" + url + "'").val();
  var birKokD = grup_no + "_kokDerecesi_" + i;
  var birKokK = grup_no + "_kokKatsayi_" + i;
  var birKokID = grup_no + "_kokIciDeger_" + i;
  birinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
  birinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
  birinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
  sonuc = document.getElementById(grup_no + "_sonuc");
  i= i + 1;
  var ikiKokD = grup_no + "_kokDerecesi_" + i;
  var ikiKokK = grup_no + "_kokKatsayi_" + i;
  var ikiKokID = grup_no + "_kokIciDeger_" + i;
  ikinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
  ikinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
  ikinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
  i = 1;

  //send request to server
  let url = '/TYT_Mat_Soru_Cozumu_Java_war_exploded/Servlet/HesaplamaIslemleri';
  let xhr = new XMLHttpRequest();
  xhr.open("POST", url, true);
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencode");
  var data;
  data = JSON.stringify(
    "birinci":[
    birKokD: birinciKokDerecesi,
    birKokK: birinciKatsayi,
    birKokID: birinciKokIciDeger],

    "ikinci":[
    ikiKokD: ikinciKokDerecesi,
    ikiKokK: ikinciKatsayi,
    ikiKokID: ikinciKokIciDeger
  ],"operator": operator
  );
  xhr.send(data);
  xhr.onload = function()
   sonuc.readOnly = true
    sonuc.value = xhr.responseText;
  

Servlet 代码:

            // Business Logic
            KokluSayiIslemleriImpl business = new KokluSayiIslemleriImpl();
    
            // Reading Request Header
            StringWriter writer = new StringWriter();
            StringBuilder buffer = new StringBuilder();
            BufferedReader reader = req.getReader();
            String line;
            while ((line = reader.readLine()) != null) 
                buffer.append(line);
            
            String data = buffer.toString();
            JSONObject jsonObj = new JSONObject(new String(data));
    
            // Creating the first object with data that getting from header
            JSONArray birinci = new JSONArray();
            birinci.put(jsonObj.get("birinci"));
            JSONObject birinciSayi = birinci.getJSONArray(0).getJSONObject(0);
            int kokDerecesi_1 = Integer.parseInt(birinciSayi.getString("birKokD"));
            double kokIciDeger_1 = Double.parseDouble(birinciSayi.getString("birKokID"));
            int kokKatsayi_1 = Integer.parseInt(birinciSayi.getString("birKokK"));
            KokluSayi koklusayi_1 = new KokluSayi(kokDerecesi_1,kokIciDeger_1,kokKatsayi_1);
            // Veri Sırası Test
            System.out.println(koklusayi_1.getKokDerecesi() + " / " + koklusayi_1.getKatsayi() + " / " + koklusayi_1.getKokIciDeger());
    
            // Creating the second object with data that getting from header
            JSONArray ikinci = new JSONArray();
            ikinci.put(jsonObj.get("ikinci"));
            JSONObject ikinciSayi = ikinci.getJSONArray(0).getJSONObject(0);
            int kokDerecesi_2 = Integer.parseInt(ikinciSayi.getString("ikiKokD"));
            double kokIciDeger_2 = Double.parseDouble(ikinciSayi.getString("ikiKokID"));
            int kokKatsayi_2 = Integer.parseInt(ikinciSayi.getString("ikiKokK"));
            KokluSayi koklusayi_2 = new KokluSayi(kokDerecesi_2,kokIciDeger_2,kokKatsayi_2);
            // Veri Sırası Test
            System.out.println(koklusayi_2.getKokDerecesi() + " / " + koklusayi_2.getKatsayi() + " / " + koklusayi_2.getKokIciDeger());
    
            // Getting the operator(which operation will processing)
            char operator = jsonObj.getString("operator").charAt(0);
    
            KokluSayi sonuc = business.dortIslem(koklusayi_1,koklusayi_2,operator);
            //send result back to client 
resp.getWriter().write("D :" + sonuc.getKokDerecesi() + " - " + "K :" + sonuc.getKatsayi() + " - " + "D :" + sonuc.getKokIciDeger());

编辑:添加动态创建代码部分的元素的阅读内容

【讨论】:

【参考方案2】:

首先,您向 HTTP 资源发出的 POST 请求不是 AJAX。如果你想异步发起一个 HTTP 请求,获取响应并写入 DOM 而不刷新整页,请先查看经典的 XmlHttpRequest 并研究其他方法。在高层次上,您的任务将是这样的,

    如果你想做一些动态的事情,用 JavaScript 构建 UI 部分。

    对于静态部分,请使用单独的 CSS 文件并将您的样式移至该文件。不要在 JavaScript 中创建所有 HTML 元素和 CSS 样式,除非您需要所有内容都是动态的。

    了解您希望从服务器端返回的内容。

您想直接从服务器端返回格式化的 HTML 吗?或者以 JSON 或 XML 等格式返回数据,并在客户端获取返回的 AJAX 响应并操作 DOM(在您的情况下为“结果”文本框)。

【讨论】:

以上是关于从 servlet 更改元素的值并将数据返回到网页而不使用 ajax 刷新的主要内容,如果未能解决你的问题,请参考以下文章

如何从 servlet 动态设置/获取复选框的值

2019年面试题1

Ajax表单提交我想通过id更改表单元素的值,以便脚本从php中的返回值进行下一次调用

PHP执行SQL并将返回数据显示到网页上为啥汉字会变成问号

servlet不能向浏览器发送html标签?

如何通过它们的值更改 PHP 中选择元素中页面的位置?