Ways to deal with dynamic javascript whose content depends on user inputs
I am working on integrating Jcrop into my web app. Jcrop has a javascript function whose content uses the dimensions of the picture uploaded by user and thus the javascript is dynamic. I have some vague idea on the approaches that I can take but not knowing how.
The sequence of events in this scenario goes like this:
- User chooses a picture to upload
- A popup shows up (ie. AJAX) to give the user the ability to crop the picture. This is done by the use of Jcrop, which requires开发者_Go百科 the javascript below.
Javascript code:
function initCropping(width, height, preview_width, preview_height) {
var jcrop = $.Jcrop('#cropbox', {
onChange: showPreview,
onSelect: showPreview,
aspectRatio: 1,
minSize: [preview_width, preview_height]
});
$('#crop').filter(':button').click( function () {
var selection = jcrop.tellSelect();
alert(selection.x + ', ' + selection.x2 + ', ' + selection.y + ', ' + selection.y2);
});
// Our simple event handler, called from onChange and onSelect
// event handlers, as per the Jcrop invocation above
function showPreview(coords)
{
if (parseInt(coords.w) > 0)
{
var rx = {{ preview_width }} / coords.w;
var ry = {{ preview_height }} / coords.h;
$('#preview').css({
width: Math.round(rx * {{ width} }) + 'px',
height: Math.round(ry * {{ height }}) + 'px',
marginLeft: '-' + Math.round(rx * coords.x) + 'px',
marginTop: '-' + Math.round(ry * coords.y) + 'px'
});
}
};
};
The problem here is that {{ width }} and {{ height }} are the dimensions of the uploaded picture, so they can't be determined until after Step 1 and thus I call the javascript dynamic.
The approaches that I have vague idea are:
- Serve that javascript from my web server
- AJAXly send the picture dimensions to the client browser and build that dynamic javascript function at the client end by another javascript function.
- Some other approaches??
Please share the approach that you would take in this scenario, how (an example would be great), and why. Thanks.
FYI. I am using Django and jQuery.
精彩评论