开发者

jQuery + Ajax: submit a single textbox to a controller

I'm working on a timesheet application. I'd like to add an autosave functionality. Let's say I have a form like this:

<form id="timesheet" action="save_timesheet.html" method="POST">
<input type="text" id="day1taskid2" />
<input type="text" id="day2taskid2" />
<input type="text" id="day3taskid2" />
<input type="text" id="day41taskid2" />
...
</form>

If a user inserts a new value (= onChange) I'd like to get that specific value and send it to my controller (using JSON/Ajax). For example: I add 2 hours to a specific textbox, and the jQuery ajax should do the update onChange. It's pretty hard to find a working example. I've seen a lot of examples using a form, but I'm not submitting the whole form, only one small textbox. There can be over 70 textboxes on one screen, depending on the amount of tas开发者_如何转开发ks to show.

What do I need? Could you give me an easy-to-understand example for this case? I'm using Spring 2.x.

Added the solution ;-)


You could do a manual ajax post with the content from the textbox you're currently in. Then in your server code handle what ever comes in:

$("[input='text']").change(function() { 
    var $this = $(this);
    $.ajax({
        url: "url/to/your/server",
        data: { name: $this.attr("id"), value: $this.val() },
        success: function(data) {
            console.log(data);
        }
    });
});

This will send a key-value pair to your server with the key being the id of the textbox, and the value would be the actual value.

So in your server code you could just check the key, and handle the value accordingly.


I'm using jQuery AJAX for the call to my controller.

My view:

function doUpdate(id, taskid){
        var x = id.value;
        var firstday = document.getElementById('firstweek').value;
        var pid = document.getElementById('projectid').value;

        if (x >=0 && x <= 24 && x != ""){
            $.post("savets.html", { hours: x, id: id.id, taskid: taskid, firstday: firstday, pid: pid }, function(data) {
                alert("callback");  
            });  
        } else {
            alert("Please enter a valid number: 0 - 24");
        }

My Controller:

@RequestMapping(value = { "/savets.html" }, method = RequestMethod.POST)
public String addTimeRecord(ModelMap model, HttpServletRequest request,
        ) {
    System.out.println("Doing the insert onUpdate with value = "
            + request.getParameter("hours") + " for ID "
            + request.getParameter("id") + " " 
            + request.getParameter("firstday")  + " " 
            + request.getParameter("taskid"));

Form:

<input type="text" onChange=doUpdate(id of my record, the taskid) />

The rest is selfexplanatory. I have hidden values in my form, I get them using Javascript. After that I call the controller which will execute the update (I did not add this code, as it is a simple check + insert)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜