在jQuery和Servlet之间传递数据

时间:2022-11-07 13:25:55

I have a HTML form:

我有一个HTML表单:

<head>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.js"></script>
    <script type="text/javascript">

        $(document).ready(function() {

            $('#convert').click(function(){

                //pairno tis times ap tin forma
                var amount = $('#amount').val();
                var from = $('#from').val();
                var to = $('#to').val();

                //kano ta dedomena ena koino string
                var dataString = "amount=" + amount + "&from=" + from + "&to=" + to;

                $.ajax({
                type: "POST",
                url: "CurrencyConverter",
                success: function(data){
                //pairno ta dedomena
                $('#results').show();

                //vazo ta dedomena sto results div tag.
                $('#results').html(data);
            }
         });
        });

        $('#swap').click(function() { 
            
            s1=$('#to').val();  
            s0=$('#from').val();  
            $('#to').val(s0);  
            $('#from').val(s1); 
        });
});

</script>


</head>
<body>
    <div class="data">
        <label for="from">Μετάτρεψε:</label>
        <input type="text" name="amount" id="amount" value="1" />
    </div>

    <div class="data">
        <label for="fromCurrency">από:</label>
        <select name="from" id="from">
          <option selected="" value="EUR">Euro - EUR</option>
          <option value="USD">United States Dollars - USD</option>
          <option value="GBP">United Kingdom Pounds - GBP</option>
          <option value="CAD">Canada Dollars - CAD</option>
        </select>
    </div>

    <div class="data">
        <label for="to">σε:</label>
        <select name="to" id="to">
          <option value="USD">United States Dollars - USD</option>
          <option value="GBP">United Kingdom Pounds - GBP</option>
          <option value="CAD">Canada Dollars - CAD</option>
          <option value="AUD">Australia Dollars - AUD</option>
          <option value="JPY">Japan Yen - JPY</option>
        </select>
    </div>
    <div class="data">
        <input type="submit" value="Μετατροπή">
        <input type="submit" name="swap" id="swap" value="αντάλλαξέ τα!">
    </div>
</div>

<div id="results"></div>
</body>
</html>

I want to extract the data from that form using the script on the top and send them to my servlet.

我想使用顶部的脚本从该表单中提取数据并将它们发送到我的servlet。

Here is my servlet code:

这是我的servlet代码:

package com.example.web;
import com.example.model.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.lang.*;
import java.util.*;

public class CurrencySelect extends HttpServlet{

        public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException{

            //response.setContentType("text/html;charset=UTF-8");

            String from = request.getParameter("from");

            String to = request.getParameter("to");

            String amount = request.getParameter("amount");

            CurrencyGenerator curr = new CurrencyGenerator();

            String res = curr.GetCurrency(from,to,amount);  

            out.println(res);

}

}

And here is my web.xml file:

这是我的web.xml文件:

    <?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    Version="2.4">
    <servlet>
        <servlet-name>CurrencyConverter</servlet-name>
        <servlet-class>com.example.web.CurrencySelect</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>CodeReturn</servlet-name>
        <servlet-class>com.example.web.CodeReturn</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Redirect</servlet-name>
        <servlet-class>com.example.web.Redirect</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ListenerTester</servlet-name>
        <servlet-class>com.example.web.ListenerTester</servlet-class>
    </servlet>


    <servlet-mapping>
        <servlet-name>CurrencyConverter</servlet-name>
        <url-pattern>/CurrencyConverter.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>CodeReturn</servlet-name>
        <url-pattern>/CodeReturn.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Redirect</servlet-name>
        <url-pattern>/Redirect.do</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ListenerTester</servlet-name>
        <url-pattern>/ListenTest.do</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>report</param-name>
        <param-value>report.html</param-value>
    </context-param> 

    <listener>
        <listener-class>com.example.model.MyServletContextListener</listener-class>
    </listener> 

</web-app>

I want to print the result in my html form page in a div I have in the end called results. I had the same script made with php and everything was working fine but with servlets. I can get my results in a new page, but I cannot take them in the same HTML page. How can I solve it?

我想在我的html表单页面中打印结果,在div中我最终称为结果。我有相同的脚本用PHP制作,一切都工作正常,但与servlet。我可以在新页面中获取结果,但我不能将它们放在同一个HTML页面中。我该如何解决?

3 个解决方案

#1


6  

Here,

$.ajax({
    type: "POST",
    url: "CurrencyConverter",
    success: function(data) {
        $('#results').show();
        $('#results').html(data);
    }
});

you have 2 problems:

你有两个问题:

  1. Your servlet is mapped on /CurrencyConverter.do, but yet you're trying to invoke it on /CurrencyConverter. You need to fix the URL.

    您的servlet映射到/CurrencyConverter.do,但是您尝试在/ CurrencyConverter上调用它。您需要修复该URL。

  2. You are not passing the query string dataString at all. You need to pass it as data option.

    您根本没有传递查询字符串dataString。您需要将其作为数据选项传递。

So, this should do:

所以,这应该做:

$.ajax({
    type: "POST",
    url: "CurrencyConverter.do",
    data: dataString,
    success: function(data) {
        $('#results').show();
        $('#results').html(data);
    }
});

Note that although cobbling the query string together yourself may work in most cases, it will fail whenever the input values contain special characters. You want to pass a JS object along instead as shown in Akhil's answer. But much better is to just use a <form> and jQuery.serialize(). See also Simple calculator with JSP/Servlet and Ajax for a kickoff example.

请注意,尽管在大多数情况下将查询字符串拼凑在一起可能会起作用,但只要输入值包含特殊字符,它就会失败。你希望传递一个JS对象,如Akhil的回答所示。但更好的是只使用

和jQuery.serialize()。另请参阅使用JSP / Servlet和Ajax的简单计算器作为启动示例。

#2


1  

/*
 Hi ,

just try changing the following code in javascript 

*/

  var dataString ={"amount":amount,"from":from,"to":to};

  $.ajax({
                type: "POST",
                data:dataString,
                url: "CurrencyConverter",
                success: function(data){
                //pairno ta dedomena
                $('#results').show();

                //vazo ta dedomena sto results div tag.
                $('#results').html(data);
            }
         });

#3


-2  

A JSP page is itself a servlet...the servlet container compiles it behind the scenes. So you can refer to the request object inside the JSP file itself. So if the form's action is the name of the HTML page itself, then the results of the form will be visible. So for example you could put this in your JSP:

JSP页面本身就是一个servlet ...... servlet容器在后台编译它。因此,您可以在JSP文件本身中引用请求对象。因此,如果表单的操作是HTML页面本身的名称,那么表单的结果将是可见的。例如,您可以将它放在JSP中:

<%= request.getParameter("amount")%>

You can also have your JSP action point at a servlet, and then have the servlet redirect back to the JSP. I don't remember the details off the top of my head, but again, this would mean that the request parameters would be visible to the JSP page.

您还可以在servlet中使用JSP操作点,然后将servlet重定向回JSP。我不记得我头脑中的细节,但这又意味着JSP页面可以看到请求参数。

#1


6  

Here,

$.ajax({
    type: "POST",
    url: "CurrencyConverter",
    success: function(data) {
        $('#results').show();
        $('#results').html(data);
    }
});

you have 2 problems:

你有两个问题:

  1. Your servlet is mapped on /CurrencyConverter.do, but yet you're trying to invoke it on /CurrencyConverter. You need to fix the URL.

    您的servlet映射到/CurrencyConverter.do,但是您尝试在/ CurrencyConverter上调用它。您需要修复该URL。

  2. You are not passing the query string dataString at all. You need to pass it as data option.

    您根本没有传递查询字符串dataString。您需要将其作为数据选项传递。

So, this should do:

所以,这应该做:

$.ajax({
    type: "POST",
    url: "CurrencyConverter.do",
    data: dataString,
    success: function(data) {
        $('#results').show();
        $('#results').html(data);
    }
});

Note that although cobbling the query string together yourself may work in most cases, it will fail whenever the input values contain special characters. You want to pass a JS object along instead as shown in Akhil's answer. But much better is to just use a <form> and jQuery.serialize(). See also Simple calculator with JSP/Servlet and Ajax for a kickoff example.

请注意,尽管在大多数情况下将查询字符串拼凑在一起可能会起作用,但只要输入值包含特殊字符,它就会失败。你希望传递一个JS对象,如Akhil的回答所示。但更好的是只使用

和jQuery.serialize()。另请参阅使用JSP / Servlet和Ajax的简单计算器作为启动示例。

#2


1  

/*
 Hi ,

just try changing the following code in javascript 

*/

  var dataString ={"amount":amount,"from":from,"to":to};

  $.ajax({
                type: "POST",
                data:dataString,
                url: "CurrencyConverter",
                success: function(data){
                //pairno ta dedomena
                $('#results').show();

                //vazo ta dedomena sto results div tag.
                $('#results').html(data);
            }
         });

#3


-2  

A JSP page is itself a servlet...the servlet container compiles it behind the scenes. So you can refer to the request object inside the JSP file itself. So if the form's action is the name of the HTML page itself, then the results of the form will be visible. So for example you could put this in your JSP:

JSP页面本身就是一个servlet ...... servlet容器在后台编译它。因此,您可以在JSP文件本身中引用请求对象。因此,如果表单的操作是HTML页面本身的名称,那么表单的结果将是可见的。例如,您可以将它放在JSP中:

<%= request.getParameter("amount")%>

You can also have your JSP action point at a servlet, and then have the servlet redirect back to the JSP. I don't remember the details off the top of my head, but again, this would mean that the request parameters would be visible to the JSP page.

您还可以在servlet中使用JSP操作点,然后将servlet重定向回JSP。我不记得我头脑中的细节,但这又意味着JSP页面可以看到请求参数。