私はjsonpを試しています。
現在、ドロップボックスフォームとテーブルを含む、以下にリストされている ajax を含む html ページがあります。最初はヘッダーのみが存在し、他のセルにデータを入力するために jsonp 応答を取得する ajax に依存します。
次に、応答phpもホストし、すべてが正しいと思いましたが、明らかにそうではありませんでした。
1つを見落としていない限り、すべての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) . ')';
?>