【发布时间】:2014-03-24 12:55:27
【问题描述】:
我有一个 php-code,可以从 RPC 服务器获取 json 数据。
<?php
error_reporting(E_ALL);
$server = 'http://pogoda.ngs.ru/json/';
// API-method
$method = 'getForecast';
// input data
$params = array('name' => 'current',
'city' => 'nsk');
//
$request = array('method' => $method,
'params' => $params);
// encode to json
$request = json_encode($request);
//
$opts = array('http' => array('method' => "POST",
'content' => $request));
// context stream
$context = stream_context_create($opts);
// get result
$result = file_get_contents($server, 0, $context);
$result = json_decode($result, true);
print_r($result);
?>
然后我尝试通过 jquery 在 javascript 中执行此操作。我找到了很多方法,但都没有奏效。
<html>
<head>
<link rel=stylesheet type="text/css" href="myCssFile.css">
<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
</head>
<body>
<?php
header('Content-type: text/html; charset=utf-8');
?>
<script>
var url = "http://pogoda.ngs.ru/json/";
var request = {};
request.method = "getForecast";
request.params = {};
request.params.name = "current";
request.params.city = "nsk";
request.params.jsonrpc = "2";
request.params.dataType = "json";
$.ajax({
url: url,
data: JSON.stringify(request),
type: "POST",
contentType: "application/json"
}).done(function(rpcRes) {
alert("ok");
}).fail(function(err, status, thrown) {
alert("Error ajax");
});
</script>
</body>
</html>
我总是有错误或什么都没有。有人知道吗?
【问题讨论】:
-
您的代码根本不可能——您不能使用 AJAX 调用来调用任意服务器。 JS AJAX 只能与最初加载 JS 代码的服务器通信。检查浏览器的错误控制台,您会看到安全警告/错误。
-
这是另一个处理相同问题的问题:stackoverflow.com/questions/2851164/…
标签: javascript php json rpc