【发布时间】:2016-03-16 05:18:57
【问题描述】:
我想通过 XMLHttpRequest 将 JSON 对象发送到 Perl 脚本 (*.cgi) 但是我无法解码 cgi 文件中的 JSON 对象。
我总是收到错误消息:
格式错误的 JSON 字符串,既不是数组、对象、数字、字符串或原子,在字符偏移量 0 处(之前 "(字符串结束)")
这是我的 javascript 代码:
//ajax communication for receiver/transceiver
function doAjaxRequest(query)
{
if(whatReq == "")
{
alert('ERROR: Request-Type undefined');
return;
}
if (window.XMLHttpRequest)
{
arequest = new top.XMLHttpRequest(); // Mozilla, Safari, Opera
}
else if (window.ActiveXObject)
{
try
{
arequest = new ActiveXObject('Msxml2.XMLHTTP'); // IE 5
}
catch (e)
{
try
{
arequest = new ActiveXObject('Microsoft.XMLHTTP'); // IE 6
}
catch (e)
{
alert('ERROR: Request not possible');
return;
}
}
}
if (!arequest)
{
alert("Kann keine XMLHTTP-Instanz erzeugen");
return false;
}
else
{
var url = "****.cgi";
var dp = document.location.pathname;
arequest.open('post', url, true);
arequest.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//receiver function
arequest.onreadystatechange = function()
{
switch (arequest.readyState)
{
case 4:
if (arequest.status != 200)
{
alert("Der Request wurde abgeschlossen, ist aber nicht OK\nFehler:"+arequest.status);
}
else
{
var content = arequest.responseText;
analyseResponse(content);
}
break;
default:
//alert("DEFAULT:" + arequest.readyState );
break;
}
}
//transceiver function
query="jsonObj=" + JSON.stringify({name:"John Rambo", time:"2pm"});
alert(query);
arequest.send(query)
}
}
这里是 cgi 文件:
#!/usr/bin/perl
use CGI qw/:standard/;
use CGI::Carp qw(fatalsToBrowser);
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $jsonObj = param('jsonObj');
my $json = JSON->new->utf8;
my $input = $json->decode( $jsonObj );
print Dumper(\$input);
你能帮帮我吗?我不知道如何访问 JSON 对象。
非常感谢。
【问题讨论】:
-
我们需要查看 JSON 字符串。尝试打印它。但猜测一下 - 因为您将它作为参数拉取,所以它是 URI 编码的。您必须先对其进行解码。
-
你不需要
arequest.send("jsonObj="+query)吗? -
我在开始查询之前发出警报:JSON 名称“John Rambo”时间“2pm”
-
我的 $test = param('jsonObj');打印自卸车(\$test);结果->脚本中的格式错误的标头。错误头=$VAR1 = \undef;: accmanagertest.cgi
-
您尚未从脚本中输出 HTTP 标头。既然你有 CGI::Carp,只需
die Dumper $test和fatalsToBrowser会为你处理它。当然,除非您明确期待 JSON 回复,在这种情况下,您必须检查您的服务器错误日志。当然,您也可以使用浏览器中的开发工具检查消息。 IE。在 Chrome 中,按 F12,转到网络,发送 AJAX 请求,单击列表中显示的内容并阅读。
标签: javascript json ajax perl