【问题标题】:jQuery and Ajax script not workingjQuery 和 Ajax 脚本不起作用
【发布时间】: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;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


【解决方案1】:

好吧,我不确定这是否是一个问题,但是您构造 URL 以调用数据的方式是不正确的。你所拥有的是

$url = 'http://www.google.com/ig/calculator?hl=en&amp;amp;q=' . $encoded_string;

这是不正确的。注意&amp;amp;q 部分。您需要按如下方式更改代码:

$url = 'http://www.google.com/ig/calculator?hl=en&q=' . $encoded_string;

【讨论】:

  • 不幸的是,这并没有解决它,但发现都一样:-)
【解决方案2】:

不能肯定地说,但我不明白你为什么要回显 eval($out . ';')?只调用没有回声的 eval。

使用 php 调用 google 的原因是由于跨域限制。但是鉴于您正在服务器中加载 json 响应,您可以将 json 响应直接返回给 jQuery。无需在服务器上解析它。试试这个,让我们知道它是否有效:

<?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;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);

header('Content-type: application/json');
echo $results;
// this should output the same data google sent, which is now in your domain so you get no cross domain errors

然后在 jQuery 中加载响应

$.ajax({
       type: "POST",
       url: "conversion.php",
       data: dataString,
       dataType:"json",
       success: function(data){
            // If I load this page http://www.google.com/ig/calculator?hl=en&q=1USD=?EUR   
            // I get {lhs: "1 U.S. dollar",rhs: "0.757174226 Euros",error: "",icc: true}
            // Assuming your call is correct and you have the same response you can now 
            // access the data like so:


       $('#result').show();

        //Put received response into result div
        $('#result').html(data.lhs + ' is equivalent to ' + data.rhs + ' Today');
       }
     });

【讨论】:

  • 感谢 Juank 的回复,很遗憾没有产生任何结果。
  • 成功回调是否在 ajax 调用中触发?如果是这样,你在 data 变量中得到了什么?
【解决方案3】:

我修复了以下问题,它适用于启用 curl 扩展的 XAMPP 1.7.7。

将您的查询更改为

$url = 'http://www.google.com/ig/calculator?hl=en&q=' . $encoded_string;

为每个键使用引号。

if (!$comment)
{
    if ($results[$i] == '{')         $out .= ' array(\'';
    else if ($results[$i] == '}')    $out .= ')';
    else if ($results[$i] == ',')    $out .= ',\'';
    else if ($results[$i] == ':')    $out .= '\'=>';
    else                             $out .= $results[$i];
}

如果#convert 是表单提交按钮,则阻止默认操作。

$("#convert").click(function (event) {
    event.preventDefault();
    var from = $("#from").val();
    // ...
});

现在发布amount=3&amp;from=EUR&amp;to=USD 会返回3 Euros = 3.9792 U.S. dollars

【讨论】:

    【解决方案4】:

    我是 stackoverflow 的新手,所以还不知道什么时候最好使用 cmets,新的答案..

    但与此同时,经过深入研究,我发现了一个非常简单的 PHP 货币转换脚本:http://www.expertcore.org/viewtopic.php?f=67&t=2161

    这实际上正是我所寻找的,非常轻巧,完全符合我的项目需求......也许它也可以帮助其他人......

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-11-18
      • 2016-09-23
      相关资源
      最近更新 更多