0

我正在上网络编程课,并试图弄清楚如何发出跨站点请求以使用出租车费查找器 API。我正在使用 Google Chrome 的开发者工具。当我运行下面的代码时,我得到了正确的响应(显示在代码块之后)。但是,我需要能够在 csCall 变量中为起点和终点传递不同的参数。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Working Echo Client</title>
    <meta charset="UTF-8" />
    <script>

    function jsonp(url) {
        var head = document.head;
        var script = document.createElement("script");

        script.setAttribute("src", url);
        console.log(script);
        head.appendChild(script);
        head.removeChild(script);
    }

    function jsonpCallback(data) {
        document.getElementById("response").textContent = JSON.stringify(data);
    }

    var csCall ="http://api.taxifarefinder.com/fare?key=mUnes8afrE3a&entity_handle=Boston&origin=42,-71&destination=42,-71.5&callback=jsonpCallback"
jsonp(csCall);
    </script>
  </head>
  <body>
      <span id="response"></span>
  </body>
</html>

响应:资源解释为脚本,但使用 MIME 类型 text/html 传输:“ http://api.taxifarefinder.com/fare?key=mUnes8afrE3a&entity_handle=Boston&origin=-41,-71&destination=-41,-71.5&callback=jsonpCallback ”。

这会在页面上准确显示:{"status":"OK","total_fare":7.69,"initial_fare":2.6,...,"distance":1849,"duration":232}

所以我然后尝试创建一个函数来接收构成起点和终点参数的经度和纬度并进行调用,但是当我尝试它时,我在代码后面收到错误消息。

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Working Echo Client</title>
    <meta charset="UTF-8" />
    <script>

    function jsonp(url) {
        var head = document.head;
        var script = document.createElement("script");

        script.setAttribute("src", url);
        head.appendChild(script);
        head.removeChild(script);
    }

    function jsonpCallback(data) {
        document.getElementById("response").textContent = data;
    }

    function makeCall(oLat, oLon, dLat, dLon) {
        var oLat = parseFloat(oLat);
        var oLon = parseFloat(oLon);
        var dLat = parseFloat(dLat);
        var dLon = parseFloat(dLon);

        csCall = "http://api.taxifarefinder.com/fare?key=mUnes8afrE3a&entity_handle=Boston&origin=" + oLat + "," + oLon + "&destination=" + dLat + "," + dLon + "&callback=" + jsonpCallback;
    }

    var csCall;
    makeCall(-42, 71, -42, 71.5);
    jsonp(csCall);
    </script>
  </head>
  <body>
      <span id="response"></span>
  </body>
</html>

控制台上的响应:资源解释为脚本,但使用 MIME 类型 text/html 传输:“ http://api.taxifarefinder.com/fare?key=mUnes8afrE3a&entity_handle=Boston&or …lementById(%22response%22).textContent%20=% 20 个数据;%20%20%20%20%20%20%20%20}”。

Uncaught SyntaxError: Unexpected token : fare:1 当我点击 fare:1 时,我被重定向到源选项卡,我在其中看到:{"status":"INVALID_CALLBACK"}。有谁知道我做错了什么可能导致无效回调?我看到的唯一变化是添加了一个连接 uri 的函数。

4

1 回答 1

0

将函数附加到字符串与调用toString函数的方法相同,它返回函数代码。您实际上要做的是附加回调的名称。

"http://api.taxifarefinder.com/fare?key=...&entity_handle=Boston"
+ "&origin=" + oLat + "," + oLon 
+ "&destination=" + dLat + "," + dLon 
+ "&callback=jsonpCallback";

此外,请确保回调位于全局命名空间中,否则注入脚本的代码将无法找到并调用它。

于 2014-04-30T23:41:26.657 回答