jQuery & Perl/CGI: add CGI content in jQuery?
$(function() {
$('input:checkbox').cha开发者_如何学Gonge(function(){
var nom = $(this).attr("value");
if ( $(this).is(':checked') ) {
$('body').append($("<div id="+nom+">Switch "+nom+"</div>"));
}
else {
$("#" + nom).remove();
}
});
Insetad of "<div id="+nom+">Switch "+nom+"</div>"
can I append SwitchGUI->new("switch-rdc-7", 24, 2)
?
No. jQuery runs in the user's browser, your perl code runs on your server; there's no way for jQuery to inject perl code into the current page and have it run. If you need to run server-side code which has an effect on what the browser is displaying, use AJAX.
It's even easier than you probably imagine. From the look of that jQuery, that's just basically an equivalent of document.write on document load. What you need is a CGI url to send back just the html for that division.
$.get("get_gui_div.cgi?param=value", function( data ) {
$( "#" + nameOfMyDiv ).html( data );
});
Depending on the complexity of your CGI, it might just be:
#!/usr/local/bin/perl -wT
use strict;
use warnings;
use SwitchGUI;
# ... deal with params ...
print SwitchGUI->new( "switch-rdc-7", 24, 2 );
But you have to keep in mind that the two layers cannot communicate between each other outside of HTTP requests and responses. Whatever you put in the code for the main document will run once to send the document. Any dynamic update will require separate request, and you'll likely have to provide parameters so the Perl knows what type of text to send back, and then it will send back an HTML fragment to be sent down to the Ajax/jQuery layer (It could also send JSON as well). So you pretty much have to have your connection points straight.
- New JavaScript can be sent with the HTML fragment
- You can have your Perl layer "paste" values into it.
- You can rig something to run server-provided JavaScript upon receipt--though that is not straightforward
In short, you send or post values to the Perl and return text that the browser can evaluate, whether HTML, JSON, XML, or even JavaScript.
精彩评论