在jQuery和Servlet之间传递数据

时间:2011-11-15 12:41:35

标签: jquery html ajax forms servlets

我有一个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>

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

这是我的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);

}

}

这是我的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>

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

3 个答案:

答案 0 :(得分:6)

下面,

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

你有两个问题:

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

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

  3. 所以,这应该做:

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

    请注意,虽然在大多数情况下将查询字符串拼凑在一起可能会起作用,但只要输入值包含特殊字符,它就会失败。你希望传递一个JS对象,如Akhil的回答所示。但更好的方法是使用<form>jQuery.serialize()。另请参阅Simple calculator with JSP/Servlet and Ajax了解启动示例。

答案 1 :(得分: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);
            }
         });

答案 2 :(得分:-2)

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

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

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