简体   繁体   中英

Calling a Servlet from Ajax

I have a Java servlet, that i need to call and pass it a variable using Ajax. I have written an Ajax script, to get the variable that needs to be passed to the servlet. However i am not sure how to do so. Any help on this matter please? This is my ajax code:

var data;
    data = "NUMBER ='" + Number + "'";

    var Key = '';
    $.ajax({
        type: "POST",
        url: "Record?DB=EMP&Table=EMP_HISTORY&",
        dataType: 'xml',
        data: {
            "Where": data
        },
        success: function(xml) {
            $(xml).find('record').each(function() {
                key  = $(this).find("PK").text();
            });
        },
        error: function(error) {
        }
    });

Your url parameter has & at last, I don't know if you have done it purposefully. However you may try this :

$.ajax({

                    url:"Record?DB=EMP&Table=EMP_HISTORY",
                    data:{Where:data},
                    contentType:"application/json; charset=utf-8",
                    dataType:"json",
                    success: function(xml) {
                      $(xml).find('record').each(function() {
                         key  = $(this).find("PK").text();
                      });
                    },
                    error:function () {

                    }
        }); 

It's unclear that which step ur in.Since that ,i would rather give u some advice.

1、if u dont use any webframework, then goto file web.xml and edit the servlet tag.configure the url and the according serlvet.Then u can overwrite the doPost() method in the servlet and receive the http request.

2、if u use webframework like struts.u can modify the configuration in struts.xml and write the according method in ur action to deal with the request.

3、if u use jsp as ur solution.u can simple do it in the jsp file. Deal with the request variables through getRequestParameter and out.print the result.

hope my advice is helpful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM