简体   繁体   中英

jQuery & Perl/CGI: add CGI content in jQuery?


I would like to add stuff to body when I click on a checkbox, it's ok, I found how to do.
My problem is that I just can add pure HTML, but I want to add Perl/CGI.
I explain:

$(function() {
    $('input:checkbox').change(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) ?
SwitchGUI is a perl module I've written, it execute a perl file, draw a switch, fill informations for each interface...
Here is SwitchGUI.pm

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.

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