AJAX

2010-12-20 6 views
2

메신저를 사용하여 HTML에서 Perl 함수를 호출합니다. im은 JavaScript가있는 HTML 페이지를 만들고 im은 AJAX를 사용하여 Perl 함수를 호출합니다. 문제는 필자의 Perl 프로그램이 매개 변수를 필요로하지 않아 호출이 간단하다는 것이다. 하지만 파일을 열어서 읽을 수있는 함수가있어서 perl 스크립트에 파일의 위치를 ​​알려줘야합니다. 따라서 AJAX 호출에서 매개 변수를 전달해야합니다. 전 통화 :AJAX

function getOption(){ 
    var selectmenu=document.getElementById("Select1") 
    selectmenu.onchange=function(){ //run some code when "onchange" event fires 
    var chosenoption=this.options[this.selectedIndex] //this refers to "selectmenu" 
    if (chosenoption.value!="nothing"){ 
    var s = chosenoption.text; 
    openFile("C:\PerlTest\test.txt"); 
    } 
    } 
    } 

EX. 매개 변수를 전달하려고 작동하지 :

function openFile(name){ 
XMLHttp.open("GET", "/cgi-bin/readFile.pl"+name, true); 
XMLHttp.onreadystatechange = function() { 
if (XMLHttp.readyState == 4) { 
    document.getElementById("TxtArea").innerHTML = XMLHttp.responseText; 
    } 
    } 
    XMLHttp.send(null); 
    } 

임 때문에이 예제의 방법으로 paremeter를 전달하는 시도 :

http://www.suite101.com/content/how-to-create-a-simple-perl-ajax-application-a136201

사람이 도와 드릴까요?

고마워요.

, HTML

function openFile(name){ 
      XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+encodeURI(name), true); 
      XMLHttp.onreadystatechange = function() { 
      if (XMLHttp.readyState == 4) { 
       var container = XMLHttp.responseText.split("\n"); 
       if (container.length>0){ 
        for (i=0; i< container.length-1;i++){ 
         document.getElementById("TxtArea").innerHTML += container[i] + " "; 
        } 
       } 
      } 
      else{ 
       document.getElementById("TxtArea").innerHTML = "333";//XMLHttp.responseText; 
      } 
      } 
      XMLHttp.send(null); 
     } 

펄 스크립트 :

#!c:/Perl/bin/perl 

use strict; 
use CGI qw/param/; 
use URI::Escape; 

print "Content-type: text/html\n\n"; 

my $file = param ('file'); 
$file = uri_unescape ($file); 

open (MYFILE, $file); 
    while (<MYFILE>) { 
     chomp; 
     print "$_\n"; 
} 
close (MYFILE); 

지금 내가 오류가 그나마 Kinopiko의 sugestion 후


, 즉 나는 다음과 같은 한 말이 자바 스크립트,하지만 내 XMLHttp.readyState 절대로 4, 그래서 내가 파일의 내용을 가져올 수 없습니다.

아마도 encodeURI를 잘못 사용 했습니까 ??

감사합니다. 모든

+0

왜 jQuery를 사용하지 않습니까? http://jquery.com/ 필자는 필요한 경우 몇 가지 예를 도울 수 있습니다. – Fred

+0

또는 prototype.js. 또는 도장. ... jQuery뿐 아니라 많은 Javascript 라이브러리가 있습니다. 그들은 모두 더 쉽게 쓸 수 있습니다. –

답변

4

먼저 당신이 물음표를 추가해야합니다

XMLHttp.open("GET", "/cgi-bin/readFile.pl?file="+name, true); 

은 또한 당신은 encodeURI를 사용하여 퍼센트 인코딩 "이름"을해야합니다. 펄 말에

, 당신은 파일의 값을 얻기 위해 CGI와 같은 모듈을 사용할 수 있습니다 그리고

use URI::Escape; 
$file = uri_unescape ($file); 
+0

매개 변수가 여전히 전달되지 않는 방법. 펄 스크립트는 실행되지 않습니다. 펄 스크립트에서 하드 코딩 된 경로를 넣으면 나는 원하는 결과를 얻는다. – Catarrunas

+0

"encodeURIComponent"가 아니라 encodeURI입니다. https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/encodeURIComponent –

+0

@Catarrunas : 왜 그 대답을 받아 들였습니까? –

1
open (MYFILE, $file); 

이어야

use CGI qw/param/; 
my $file = param ('file'); 

open (MYFILE, $file) or die "Cannot open file $file: $!\n";