所以我目前正在尝试使用jquery,curl,ajax和Google API来实现货币转换脚本,但是我遇到了一些问题。jQuery和Ajax脚本不工作
因此,这里是jQuery的AJAX +
$(document).ready(function() {
$("#convert").click(function() {
var from = $("#from").val();
var to = $("#to").val();
var amount = $("#amount").val();
//Make data string
var dataString = "amount=" + amount + "&from=" + from + "&to=" + to;
$.ajax({
type: "POST",
url: "conversion.php",
data: dataString,
success: function(data){
$('#result').show();
//Put received response into result div
$('#result').html(data);
}
});
});
});
这里就是我在conversion.php
<?php
// sanitizing input using built in filter_input available from PHP 5.2
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_INT);
$from = filter_input(INPUT_POST, 'from', FILTER_SANITIZE_SPECIAL_CHARS);
$to = filter_input(INPUT_POST, 'to', FILTER_SANITIZE_SPECIAL_CHARS);
// building a parameter string for the query
$encoded_string = urlencode($amount) . urlencode($from) . '%3D%3F' . urlencode($to);
$url = 'http://www.google.com/ig/calculator?hl=en&amp;q=' . $encoded_string;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
$results = curl_exec($ch);
// this is json_decode function if you are having PHP < 5.2.0
// taken from php.net
$comment = false;
$out = '$x=';
for ($i=0; $i<strlen($results); $i++)
{
if (!$comment)
{
if ($results[$i] == '{') $out .= ' array(';
else if ($results[$i] == '}') $out .= ')';
else if ($results[$i] == ':') $out .= '=>';
else $out .= $results[$i];
}
else $out .= $results[$i];
if ($results[$i] == '"') $comment = !$comment;
}
// building an $x variable which contains decoded array
echo eval($out . ';');
echo $x['lhs'] . ' = ' . $x['rhs'];
现在的问题是,当我点击转换按钮,它也会输出全#results div中的网页,而不是来自conversion.php的$ x
我已经花了整整一天的时间,所以任何帮助,非常感谢。
仅供参考 - 卷曲已安装并正常工作
你说什么“输出整个网页”是什么意思?它是conversion.php文件本身的内容吗?您也可以从浏览器或curl命令行尝试url“conversion.php”(以及params),看看它是否正常工作。 – rsmoorthy 2012-01-28 17:33:59
对不起,我指的是我正在测试脚本的网页,因此在#result中显示整个网页(标题,导航菜单,内容等)。 – Danny 2012-01-28 17:40:42
在您的成功函数中尝试console.log(数据)。检查您的浏览器调试器(如Firebug)以查看从服务器收到的POST请求和响应。这可能会有所帮助。 – rsmoorthy 2012-01-28 17:49:55