开发者

Refreshing specific input values with Express.js

Quick Express.js question. I've been building a simple rpg charactersheet app over the past couple of days to get my feet wet with node, express and web programming in general. Anyway I'm stuck on something that I suspect is simple but I haven't been able to find an answer to yet. Basically I have a form built that holds stat values so let's say x, y, z. OK, then I have a button that rolls against one of those stats, basically rolling dice and adding x, y, or z depending and returns the value. All right, everything up to that works fine what I'm getting stuck on is figuring out how I ca开发者_如何学运维n refresh a single input textbox without clearing the rest of the form, specifically when I return the di roll I want to input that value in the 'results' textbox but keep the values static in x, y, z.

I've tried a few different things like putting the result textbox on it's own partial and rendering that partial but that then removes the rest of the page (rendering only that partial) I can render the entire index and get the result to populate but that wipes the rest of the values for x, y, z.

In a case like this what's the best practice to achieve that goal? Should I write out the values for x, y, z to an array and pass them back when I pass back the results? I'm quite sure that would work but it doesn't seem like the most efficient way to do things.

Should I be implementing the refresh of the results box on the client side instead after the server's returned the results? If so how would I do that?

Thanks, logos


I believe your two major options are to (1) perform the numeric calculation on the client-side and update the input box directly, or (2) perform an Ajax request and use the response from the server to update the text box in a similar fashion.

Here are some more details and some examples/links to hopefully get you started.

1. Perform the calculation on the client side.

I assume you are currently submitting a form when upon clicking the button that rolls for the stat; instead. you can set up the button click so that it calls a JavaScript function you've defined on your page that performs the same calculation that you would normally perform on the server.

Here's a simple example that uses jQuery to attach click-handlers to the buttons and updates the values.

2. Perform the update via Ajax

By default, when you submit a form, the page refreshes and is replaced with the complete response from the server. Ajax allows you to submit data to the server in the background, and then get data back from the server which you can use to update your web page, without a refresh.

For more information, you may want to check out these links:

  • how to use jQuery ajax calls with node.js on Stack Overflow
  • Ajax to refresh a partial view using express and JQuery? on Stack Overflow
  • jQuery ajax and getJSON documentation
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜