【发布时间】:2012-01-28 17:15:31
【问题描述】:
所以我目前正在尝试使用 Jquery、curl、ajax 和 Google api 实现货币转换脚本,但是我遇到了一些问题。
所以这里是 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
我现在已经花了一整天的时间,所以非常感谢任何帮助。
仅供参考 - Curl 已安装并正常工作
【问题讨论】:
-
你说的“输出整个网页”是什么意思?是conversion.php文件本身的内容吗?您还可以从浏览器或 curl 命令行尝试 url “conversion.php”(连同参数),看看它是否正常工作。
-
抱歉,我指的是我正在测试脚本的网页,所以在#result 中它会显示整个网页(标题、导航菜单、内容等)。
-
在你的成功函数中尝试 console.log(data)。检查您的浏览器调试器(如 Firebug)以查看发送的 POST 请求和从服务器接收到的响应。这可能会有所帮助。
标签: php jquery ajax curl google-api