将外部纯文本内容读入字符串 [英] Reading external plain text content into string

查看:97
本文介绍了将外部纯文本内容读入字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的CGI脚本,可以根据需要生成纯文本内容。例如, http://1.2.3.4/hello.cgi?name=Joe 将返回 Hello Joe!

I have a simple CGI script that would generate plain text content on demand. For example, http://1.2.3.4/hello.cgi?name=Joe would return Hello Joe!.

如何在Javascript中将其读入字符串?

How can I read this into a string in Javascript?

name     = "Joe";
url      = "http://1.2.3.4/hello.cgi?name=" + name;
greeting = loadThis(url);

我是Javascript的新手,所以即使是天真的方法(即不需要URL转义...... )对我有帮助:))

I'm new to Javascript, so even naive approach (i.e. no need to URL escape...) will be helpful for me :)

推荐答案

基于此 JavaScriper.net上的常见问题解答,我找到了适合我的解决方案。但是,被调用的脚本必须与调用者在同一台机器上,否则我会从浏览器中获得安全性错误。

Based on this FAQ on JavaScriper.net, I have found solution that works for me. However, the called script must be on the same machine as the caller, otherwise I get security errors from browsers.

显然这就是@Makkes提到的。但是,我现在非常高兴在同一台机器上安装hello.cgi。

Apparently this is what @Makkes mentioned. However, I'm perfectly happy with having the hello.cgi on the same machine for now.

以下是代码:

function loadThis(localuri) {
    var oRequest = new XMLHttpRequest();

    var sURL = 'http://'
        + self.location.hostname
        + localuri;

    oRequest.open('GET',sURL,false);
    oRequest.setRequestHeader('User-Agent',navigator.userAgent);
    oRequest.send(null);

    if (oRequest.status==200) return(oRequest.responseText);
    else alert('Error executing XMLHttpRequest call!');
}

name        = "Joe";
localuri    = "/hello.cgi?name=" + name;
greeting    = loadThis(localuri);

(当然,这不会正确处理带有空格或特殊字符的名称,但这是另一个故事。 )

(Of course, this would not handle names with spaces or special characters correctly, but that's another story.)

这篇关于将外部纯文本内容读入字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆