Google Closure Compiler:程序访问问题

Chr*_*son 1 php api jquery curl google-closure-compiler

我试图以编程方式访问Closure Compiler工具,但是在PHP和JavaScript方面都存在问题.这是一个快速而肮脏的PHP脚本,我只是为了解决编译器的REST API:

<?php
if (!empty($_POST)) {
echo '<pre>';
print_r($_POST);
echo '</pre><br />';
  foreach ($_POST as $k => &$v) $v = urlencode($v);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POST, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
  curl_setopt($ch, CURLOPT_URL, 'http://closure-compiler.appspot.com/compile');
  echo curl_exec($ch);
} else {
  echo "
    <html>
      <body>
        <form action='' method='post'>
          <p>Type JavaScript code to optimize here:</p>
          <textarea name='js_code' cols='50' rows='5'>
            function hello(name) {
              // Greets the user
              alert('Hello, ' + name);
            }
            hello('New user');
          </textarea>
          <input type='hidden' name='compilation_level' value='WHITESPACE_ONLY' />
          <input type='hidden' name='output_format' value='json' />
          <input type='hidden' name='output_info' value='compiled_code' />
          <input type='hidden' name='warning_level' value='VERBOSE' />
          <br /><br />
          <input type='submit' value='Optimize' />
        </form>
      </body>
    </html>";
}
Run Code Online (Sandbox Code Playgroud)

我看到的输出是:

Array
(
    [js_code] =>               function hello(name) {
                // Greets the user
                alert(\'Hello, \' + name);
              }
              hello(\'New user\');

    [compilation_level] => WHITESPACE_ONLY
    [output_format] => json
    [output_info] => compiled_code
    [warning_level] => VERBOSE
)

Error(13): No output information to produce, yet compilation was requested.
Run Code Online (Sandbox Code Playgroud)

我想,也许我的cURL选项有问题.所以我尝试了JavaScript(通过jQuery.post()调用).我在随机的Firefox窗口中" jQuerify "并在Firebug控制台中运行以下代码:

$.post('http://closure-compiler.appspot.com/compile',
  {
   'js_code': "function hello(name) {/*Greets the user*/alert('Hello, ' + name);}",
   'compilation_level': 'SIMPLE_OPTIMIZATIONS',
   'output_format': 'text',
   'output_info': 'compiled_code'
  },
  function(response) {
    alert(response);
  }
);
Run Code Online (Sandbox Code Playgroud)

"Net"面板显示403错误.

我错过了什么?

Ger*_*umm 5

根据API文档

The request must always have a Content-type header of application/x-www-form-urlencoded
Run Code Online (Sandbox Code Playgroud)

在你的代码中没有看到

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/x-www-form-urlencoded'
));
Run Code Online (Sandbox Code Playgroud)

之前 curl_exec()