簡體   English   中英

將數據傳遞給CGI腳本並使用jQuery.ajax返回

[英]Pass data to CGI script and back with jQuery.ajax

我正在使用jQuery.ajax()將一些HTML表單數據發送到服務器上的Perl腳本,然后將一些數據返回給前端。

優選地,數據應該是文本/字符串格式。 我還需要將它保存為變量,以便在jQuery函數中進一步使用。

我已經設置了HTML代碼, JavaScript代碼和CGI Perl腳本,但是當JavaScript工作時,與CGI Perl腳本的連接不是,我總是收到錯誤消息: “腳本調用不成功”

也許有人可以告訴我錯誤在哪里? 我不完全確定如何將變量從Perl腳本返回到服務器。

由於我還是jQuery和JavaScript的新手並且以前沒有使用異步調用,所以任何幫助都將非常感激。

這是我的代碼:

HTML代碼:(用戶使用其名字和名稱填寫表單:

<html>
  <head>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
    <script type="text/javascript" src="get_names.js"></script>
  </head>
  <body>
    <div id="loginContent" class="container">
        <div id="loginResult" style="display:none;">
        </div>
        <form id="loginForm" name="loginForm" method="post" action="">
        <fieldset>
            <legend>Enter information</legend>
            <p>
            <label for="firstname">First name</label>
            <br />
            <input type="text" id="firstname" name="firstname" class="text" size="20" />
            </p>
            <p>
            <label for="name">Name</label>
            <br />
            <input type="test" id="name" name="name" class="text" size="20" />
            </p>
            <p>
            <button type="submit" class="button positive">
             Login
            </button>
            </p>
        </fieldset>
        </form>
    </div>
  </body>
</html>

JavaScript代碼:

$(document).ready(function(){
  $("form#loginForm").submit(function() { // loginForm is submitted


var firstname = $('#firstname').attr('value'); // get first name
var name = $('#name').attr('value'); // get name

if (firstname && name) { // values are not empty
    $.ajax({
        type: "POST",
        url: "/cgi-bin/perl_script.cgi", // URL of the Perl script

        // send firstname and name as parameters to the Perl script
        data: "firstname=" + firstname + "&name=" + name,

        // script call was *not* successful
        error: function() { 
            alert("script call was not successful");
        }, 

        // script call was successful 
        // perl_data should contain the string returned by the Perl script 
        success: function(perl_data){
            alert("Your name is: " + perl_data)
        }
    });   
}

else {
  $('div#loginResult').text("Enter your name");
  $('div#loginResult').addClass("error");
}

$('div#loginResult').fadeIn();
return false;
  });
});

Perl代碼:

#!/usr/bin/perl -w
use CGI;
use strict;
use warnings;

# read the CGI params
my $cgi = CGI->new;
my $firstname = $cgi->param("firstname");
my $name = $cgi->param("name");

my $completename = $firstname . $name;

print $completename;

問題出在Perl程序中。 它不編譯。 它不會發送所需的HTTP標頭。 添加print $cgi->header('text/plain;charset=UTF-8'); 或類似的,並注意編碼適合內容類型的輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM