我在一个web编程类中,试图找出如何使用taxifarefinder API进行跨站点请求。我正在使用Google Chrome的开发人员工具。当我运行下面的代码时,我得到了正确的响应(在代码块后显示)。 但是,我需要能够在csCall变量中传入起始位置和目标位置的不同参数。使用JSONP进行远程Ajax调用时出现无效的回调错误
<!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 =%20data;%20%20%20% 20%20%20%20%20}”。
未捕获的SyntaxError:意外的标记:车费:1 当我点击票价:1,我重定向到源标签,让我看到: {“地位”:“INVALID_CALLBACK”}。 有谁知道我在做什么错误,可能导致无效回调?我看到的唯一变化是添加了一个函数来连接uri。