0
我正在試驗jsonp。使用JSONP使用Ajax時未獲得預期的響應
目前我有一個html頁面,它包含下面列出的ajax,其中包含一個下拉框窗體,以及一張表。只有頭文件在那裏開始,它依賴於Ajax獲取jsonp響應以填充其他單元格。
然後我有我的迴應PHP也託管,我認爲一切都是正確的,但顯然不是。
我所有的ID似乎是正確的,除非我忽視了一個,所以我真的不明白爲什麼我所得到的是來自jsonp頁面的錯誤響應。
html頁面:
<html>
<head>
<title>Car Queries</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#submitbutton").click(function()
{
$.ajax(
{
url: "https://example.com/jsonServer.php",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
data: { car: $("#carselection").val()},
success: function(data)
{
if(data.name == "error")
{
$("#outputcarname").text("There is no such car available"),
$("#price").text(" "),
$("#mpg").text(" ");
}
else
{
$("#outputcarname").text("data.name"),
$("#price").text("data.price"),
$("#mpg").text("data.mpg ");
}
},
error: function()
{
$("#outputcarname").text("There is a problem with the server"),
$("#price").text(" "),
$("#mpg").text(" ");
}
});
return false;
});
});
</script>
</head>
<body>
<h1>Cars Cars Cars!</h1>
<form action="" method="POST">
<select id="carselection">
<option selected="selected">Pick a Car</option>
<option value="Maxima">Maxima</option>
<option value="Element">Element</option>
<option value="Prius">Prius</option>
</select>
</br></br>
<input type="submit" id="submitbutton" value="Submit">
</form>
</br>
<center><table>
<tr>
<th>Car Name</th>
<th>Price</th>
<th>MPG</th>
</tr>
<tr>
<td id="outputcarname"></td>
<td id="price"></td>
<td id="mpg"></td>
</tr>
</table></center>
</body>
</html>
響應JSONP/PHP:
<?php
$cars = array('Maxima' => array('price' => '$32,780', 'mpg' => '24'),
'Prius' => array('price' => '$25,565', 'mpg' => '49'),
'Element' => array('price' => '$22,075', 'mpg' => '22'));
if(array_key_exists($_GET['carselection'], $cars))
{
$carname = $_GET['carselection'];
$results = array('name' => $carname, 'price' => $cars[$carname]['price'], 'mpg' => $cars[$carname]['mpg']);
}
else
{
$results = array('name' => 'error');
}
$callback = htmlentities($_GET['callback'], ENT_QUOTES);
print $callback . '(' . json_encode($results) . ')';
?>