我正在尝试在 ajax 请求中传递 JSON 字符串。这是我的代码。
NewOrder = JSON.stringify (NewOrder);
alert (NewOrder);
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: "mydata="+ NewOrder
};
$http(req)
.success(function (data, status, headers, config) {
alert ('success');
})
.error(function (data, status, headers, config) {
alert (status);
alert (data);
alert ('Error')
});
alert (NewOrder) 给出 -
{"ItemList":[{"ItemName":"Quality Plus Pure Besan 500 GM","Quantity":1,"MRP":"28.00","SellPrice":"25.00"}],"CustomerID":1,"DeliverySlot":2,"PaymentMode":1}
这似乎是一个有效的 JSON 字符串。
但是在脚本方面我遇到了以下错误。在这一行
my $decdata = decode_json($cgi->param('mydata'));
格式错误的 JSON 字符串,既不是数组、对象、数字、字符串或原子,位于字符偏移量 0(在“(字符串结尾)”之前)
有人可以帮我解决这个错误吗?
最佳答案
$cgi->param('myData')
返回查询参数字符串“mydata”,在您的情况下不会发送。
您在 http post 负载的请求正文中发布 json 数据,而不是作为查询/表单参数。在这种情况下,您需要一些其他函数来读取服务器端脚本中请求正文的内容。
恰好是:
我的 $data = $query->param('POSTDATA');
如此处所述:http://search.cpan.org/~lds/CGI.pm-3.43/CGI.pm#HANDLING_NON-URLENCODED_ARGUMENTS
您还应该从您发布的正文中的 json 中删除“mydata=”,因为 http 请求有效负载正文没有参数名称(它们仅用于查询/表单参数)。
你的结束代码应该是这样的:
var req = {
url: '/cgi-bin/PlaceOrder.pl',
method: 'POST',
headers: { 'Content-Type': 'application/json'},
data: NewOrder
};
和服务器端:
my $decdata = decode_json($query->param('POSTDATA'));
关于javascript - 从 AngularJS 传递 JSON 时格式错误的 JSON 字符串错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31099298/