我正在尝试访问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()调用)。我在随后的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);
}
);
“Net”面板显示403错误。
我错过了什么?
答案 0 :(得分: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()
答案 1 :(得分:1)
Ajax(通过jQuery或其他)因同源策略而无效。 ( ajax请求在同一个域中受到限制,除非结果需要jsonp )
只需使用您的示例发布信息,就可以在http://www.jsfiddle.net/RySLr/
中看到所以它必须是@German Rumm所提到的......