【问题标题】:javascript get data from rpcjavascript从rpc获取数据
【发布时间】: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


【解决方案1】:

Marc B 的评论很接近,但并不完全正确。您不能向不受您控制的服务器发出任意 AJAX 请求。安全策略可以防止这种情况发生。

如果您控制两个端点,您可以添加一个Access-Control-Allow-Origin 标头以允许另一个域向它发出请求,但如果您不这样做,那么您就不走运了。

您最好的选择可能是继续使用获取数据的 PHP 脚本,如果您需要在页面中实时更新,则使用 AJAX 调用该脚本 - 这样您就可以使用自己的服务器作为一种代理,让它工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-03
    • 2011-12-27
    • 1970-01-01
    • 2019-03-14
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多