2011-01-10 91 views
1

我试图访问Closure Compiler工具programmatically,但有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>"; 
} 

我看到的输出是:

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. 

我想,也许有一个问题我的cURL options。所以我尝试了JavaScript(通过调用jQuery.post())。我“jQuerify” D随机Firefox窗口,跑在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); 
    } 
); 

‘网’面板显示403错误这一点。

我错过了什么?

回答

5

根据API文档

The request must always have a Content-type header of application/x-www-form-urlencoded 

没有看到,在你的代码

添加

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

curl_exec()

+0

谢谢!必须有十几次阅读权利。 – 2011-01-10 18:19:33

1

阿贾克斯(通过jQuery 或以其他方式)将不起作用,因为同源政策。 (Ajax请求都在同一个域中的限制,除非JSONP预计为结果

只需用你的例子来发布信息,其工作原理为http://www.jsfiddle.net/RySLr/

看到因此,它必须是什么@German Rumm提到..

+0

杜。我应该意识到这一点。谢谢! – 2011-01-10 18:18:16