我正在使用ajax創建一個可以監控SEPTA總線時間表的網站。但是,當向URL發送請求時,我的網站總是出錯(http://www3.septa.org/hackathon/TransitView/?route=ROUTE_NUAMBER&callback=?
)。如何使用ajax動態獲取總線時間表
這是我使用之前的功能:
function getSchedule(){
var route = $("#route");
var myURL = "http://www3.septa.org/hackathon/TransitView/?route=" + route.val() + "&callback=?";
$.ajax({
type: "GET",
url: myURL,
contentType: "application/json; charset-utf-8",
data: "()",
datatype: "jsonp",
success: function(json){
var myTable = "<tr><td>Vehicle ID</td> <td>Block ID</td> <td>Direction</td> <td>Destination</td> <td>Delay</td></tr>";
for(var i=0; i<json.bus.lenght; i++){
var vehicleNumber = json.bus[i].VehicleID;
var blockID = json.bus[i].BlockID;
var direction = json.bus[i].Direction;
var destination = json.bus[i].destination;
var offset_sec = json.bus[i].Offset_sec;
var offset_sec_n = parseInt(offset_sec);
if(offset_sec_n >= 120){
var delay = "Delay";
}
else{
var delay = "On Time";
}
myTalbe += "<tr><td>" + vehicleNumber + "</td><td>" + blockID + "</td><td>" + direction + "</td><td>" + destination + "</td><td>" + delay + "</td></tr>";
}
myTalbe = "<tb>" + myTable + "</tb>";
document.getElementById("schedule").innerHTML = myTable;
},
error: function(xhr, ajaxOptions, thrownError){
document.getElementById("schedule").innerHTML = "Error fetching "
+ myURL;
}
})
}
它得到此erorr消息:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
然後,我有一個修改建議:
url: "http://ww3.septa.org/Hackathon/TransitView/",
data: {route: route_val}, //where route_val is whatever variable stores the route number. it can be named route, I just wanted to clarify the key vs value
jsonpCallback: "callback_func" //note that this is a string.
但我不是很明白是什麼是。我如何使我的網絡工作?
@Phil - 我不認爲這是另一個問題(我不是說他們沒有一些共同的點,當然)的副本。這一個已經試圖使用JSONP,並且OP正在詢問如何使用回調函數。這似乎更具體。 – nnnnnn
兩個錯字...1)刪除'data:'()'',因爲您已經在URL中指定了查詢參數,並且「()」沒有任何用處。 2)將'datatype'更改爲'dataType'(大寫「T」) – Phil
@nnnnnn你是對的。我認爲遠程站點不是啓用JSONP,但它是 – Phil