将对象从 javascript 传递到 Perl dancer 框架
Pass object from javascript to Perl dancer framework
我有以下 ajax
代码将值传递给 dancer framework
。
BookSave: function(data) {
### data is an object that contain more than one key value pair
var book = Book.code;
$.ajax ({
type: "GET",
url : 'textbook/save/' + book + '/' + data,
success: function(data) {
if(data.status == 1) {
alert("success");
} else {
alert("fail");
}
},
});
},
在舞者中:
any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
set serializer => 'JSON';
my $book = params->{book};
my $data = params->{data}; ## This I am getting as object object instead of hash
};
有什么方法可以从 js 传递对象并在 dancer 中获取哈希值吗?
首先,考虑使用 http PUT 或 POST 动词,而不是 GET。这样做不仅在语义上更正确,它还允许您在 http 正文中包含更复杂的对象,例如您的 'data' 哈希(序列化,根据我在下面的评论)。
我使用 Dancer 的本机 AJAXy 方法取得的成功有限,而且在某些版本的 Firefox 中存在一个导致问题的错误。因此,我先序列化然后反序列化 JSON 对象。
建议的更改(注意我也建议更改您的路线):
$.ajax ({
type: "PUT",
url : '/textbook/' + book,
data: {
myhash : JSON.stringify(data)
},
dataType: 'json',
contentType: 'application/json',
success: function (response) {
if (response.status == 1) {
alert("success")
} else {
alert("fail")
}
}
})
您的 Perl Dancer 代码更改如下:
any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
set serializer => 'JSON';
my $book = param('book');
my $data = from_json(param('myhash'));
};
我没有去测试这段代码,但它至少应该给你一个很好的起点来完成这个问题。
祝你项目顺利!
我有以下 ajax
代码将值传递给 dancer framework
。
BookSave: function(data) {
### data is an object that contain more than one key value pair
var book = Book.code;
$.ajax ({
type: "GET",
url : 'textbook/save/' + book + '/' + data,
success: function(data) {
if(data.status == 1) {
alert("success");
} else {
alert("fail");
}
},
});
},
在舞者中:
any [ 'ajax', 'get' ] => '/save/:book/:data' => sub {
set serializer => 'JSON';
my $book = params->{book};
my $data = params->{data}; ## This I am getting as object object instead of hash
};
有什么方法可以从 js 传递对象并在 dancer 中获取哈希值吗?
首先,考虑使用 http PUT 或 POST 动词,而不是 GET。这样做不仅在语义上更正确,它还允许您在 http 正文中包含更复杂的对象,例如您的 'data' 哈希(序列化,根据我在下面的评论)。
我使用 Dancer 的本机 AJAXy 方法取得的成功有限,而且在某些版本的 Firefox 中存在一个导致问题的错误。因此,我先序列化然后反序列化 JSON 对象。
建议的更改(注意我也建议更改您的路线):
$.ajax ({
type: "PUT",
url : '/textbook/' + book,
data: {
myhash : JSON.stringify(data)
},
dataType: 'json',
contentType: 'application/json',
success: function (response) {
if (response.status == 1) {
alert("success")
} else {
alert("fail")
}
}
})
您的 Perl Dancer 代码更改如下:
any [ 'ajax', 'put' ] => '/textbook/:book' => sub {
set serializer => 'JSON';
my $book = param('book');
my $data = from_json(param('myhash'));
};
我没有去测试这段代码,但它至少应该给你一个很好的起点来完成这个问题。
祝你项目顺利!