Прошло некоторое время с тех пор, как я написал PHP и AJAX. Поэтому, пожалуйста, медведь со мной.Как подключиться к внешнему API с помощью JSON?
Я пытаюсь использовать API AltosResearch для диаграмм истории/счетов Comp. API doc at: https://docs.google.com/document/pub?id=1hHPmUEuV5ekqXTLN8RcEOyzhiBLZSz2eFUuV1_Mu7fg#h.fc47gnpln3dt
Пользователь вводит домашний адрес в указанной форме. Запрос ajax получит информацию JSON от AltosResearch. Затем будут предоставлены историческая информация и домашние сопоставители. Однако я не получаю информацию от Altos. Я знаю, что не могу использовать JSONP, так как я подключаюсь к внешнему хосту. Поэтому я использовал завиток для получения информации. Что я здесь делаю неправильно?
Пожалуйста, помогите. Спасибо.
Ответ JSON из Альтос имеет следующий формат:
{
"list": [
{
"unit_number": "",
"property_id": "a08373408624b1570ff6aafb77498308",
"baths": "1.00",
"zip": "94086",
"geocode_accuracy": "",
"residence_sqft": "765",
"year_built": "1942",
"street_name": "CALIFORNIA",
"state": "CA",
"lot_sqft": "4900",
"data_capture_date": "2011-08-26",
"city": "SUNNYVALE",
"days_on_market": "",
"price": "388000",
"beds": "2.00",
"street_address_raw": "800 E CALIFORNIA AV",
"street_direction": "EAST",
"longitude": "",
"street_number": "800",
"latitude": "",
"listing_entry_id": "caf478d031f90abd0131fe7caff77ea7",
"residence_type": "single_family",
"street_type": "AVENUE"
}
],
"responseCode": 200,
"apiVersion": 1
}
Вот мой JS файл:
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script>
$(document).ready(function(){
$("#altos").on('submit', function(event) {
function errorFunction() {
document.getElementById('result').innerHTML = "There was an error with JSON's callback function!";
}
// Request the JSON and process it
$.ajax({
type: 'GET',
dataType: 'json',
async: true,
url: 'http://data.altosresearch.com/altos/app',
success: function(data) {
console.log(data);
document.getElementById("result").innerHTML= "Property IDs: " + data.list[0].property_id + data.list[0].listing_entry_id;
},
error: function() {
errorFunction();
}
});
return false;
event.preventDefault();
});
});
</script>
Вот мой PHP-файл:
// Using GET
$c = curl_init();
curl_setopt($c, CURLOPT_URL, "http://data.altosresearch.com/altos/app");
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$page_data = curl_exec($c);
curl_close($c);
// Access data with GET or POST via retrieve_page fun
function retrieve_page($url, $post_parameters = null) {
// Connect and fetches data
$query_string = null;
if(!is_null($post_parameters)) {
if(!is_array($post_parameters)) {
die("Form parameters need to be in an array format");
}
}
// Build query string
$query_string = http_build_query($post_parameters);
}
// Configure connection to use query string as POST data
$ch = curl_init();
if ($query_string) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return_data = curl_exec($ch);
curl_close($ch);
return $return_data;
}
// Extract params from the form
$qs = http_build_query(array(
"pai" => "755110180",
"apiv" => "1",
"service" => "listinghistory",
"st" => $_REQUEST["st"],
"c" => $_REQUEST["c"],
"z" => $_REQUEST["z"],
"addr" => $_REQUEST["addr"]
));
if(isset($_GET['st'], $_GET['c'], $_GET['z'], $_GET['addr'])) {
$pai = $_GET['pai'];
$apiv = $_GET['apiv'];
$service = $_GET['service'];
$st = $_GET['st'];
$c = $_GET['c'];
$z = $_GET['z'];
$addr = $_GET['addr'];
$qs['pai'] = $pai;
$qs['apiv'] = $apiv;
$qs['service'] = $service;
$qs['st'] = $st;
$qs['c'] = $c;
$qs['z'] = $z;
$qs['addr'] = $addr;
}
header('Content-type: application/json');
echo json_encode($qs);
$page = retrieve_page("http://data.altosresearch.com/altos/app?$qs");
echo ("<hr>page info: " . $page . ".<hr>");
Спасибо вам
Итак, как мне обойти это? Является ли curl лучшим способом для получения json-объектов из внешнего API через PHP или есть ли другие варианты? Благодарю. – yamenator