我将 JSON 请求发布到远程服务。一切都很好,服务很好,它对我有反应。但我没有从远程服务返回数据。如何通过 JQuery 通过 .post 从远程 json 服务获取数据?为什么这个例子返回数据——“null”:
<SCRIPT>
$(function() {
$('#zzz').click(function() {
$('#lak').html('wait...');
$.post(
'http://127.0.0.1:3000/test',
"{\"ipaddr\":\"192.168.132.58\"}",
function(data) { alert(data); },
"json"
)
});
});
</SCRIPT>
但是 TCP 嗅探器向我显示该服务返回了一些数据:
HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Type: application/json
X-Powered-By: Mojolicious (Perl)
Date: Thu, 02 Sep 2010 06:17:10 GMT
Content-Length: 37
Server: Mojolicious (Perl)
{"status":"OK","result":"successful"}
解决了:
<SCRIPT>
$(function() {
$('#clickme').click(function() {
$.getJSON('http://domain.tld/test/?foo=bar&callback=?',
function(jsonp) {
$('#jsonp-example').html(jsonp.result);
});
});
});
</SCRIPT>
<div id="jsonp-example"><a id="clickme" href="javascript:void()">Click me</a></div>
Mojolicious JSONP 服务示例:
# /test/?foo=bar&callback=smth
get '/test' => sub {
my $self = shift;
my $foo = $self->param('foo') || '';
my $callback = $self->param('callback') || 'jsonp';
...
my $json = $self->render(
json => {
'status' => 'OK',
'result' => 'successful'
},
partial => 1);
$self->render(data => "$callback($json)", format => 'js');
} => 'test';