![](/img/trans.png)
[英]I want to initialize my observable when I get 404 response from the API
[英]I have an API, I want to get the data from api response
這是API: https://pincode.saratchandra.in/api/pincode/{any pin code}
: https://pincode.saratchandra.in/api/pincode/{any pin code}
示例:我有https://pincode.saratchandra.in/api/pincode/500022
上面的API請求返回以下數據:
{“狀態”:200,“數據”:[{“ taluk”:“ Khairatabad”,“州名稱”:“ TELANGANA”,“ region_name”:“海得拉巴市”,“密碼”:“ 500022”,“辦公室名稱”: “中央秘書處SO”,“ id”:4686,“ division_name”:“ Hyderabad City”,“ district”:“ Hyderabad”,“ delivery_status”:“ Delivery”,“ circle_name”:“ Andhra Pradesh”}]}
我想在我的網頁上顯示如下
塔魯克:凱塔塔巴德
州名:Telengana
等等
我想要一個從用戶那里接收密碼並使用特定密碼進行請求的表單,並獲取該密碼的數據並將其顯示在網站上。
我一直在努力奮斗,但是我找不到實現它的方法。
您可以使用Ajax或jQuery.getJSON()訪問它
$.getJSON( "https://pincode.saratchandra.in/api/pincode/500022", function( data ) {
/* data is the fetch result from the api
* you can access taluk field by data.data.taluk
* or state name by data.data.state_name */
console.log(data);
});
但是,如果您的網站托管在其他地方,那么您將遇到CORS(跨源資源共享)問題。
除非將pincode.saratchandra.in服務器配置為允許CORS,否則無法使用這種方法在瀏覽器中執行此操作。 您的服務器可以為您提出請求,或者您可以聯系pincode.sratchandra.in以允許您的域/服務器訪問數據。
您還可以使用php或其他服務器端腳本來訪問數據。 例如在php中,除非服務器(pincode.sratchandra.in)允許您這樣做。
這是php中的示例:
<?php
$json = file_get_contents('https://pincode.saratchandra.in/api/pincode/500022');
$obj = json_decode($json);
echo 'Taluk: ' + $obj->data->taluk;
echo '<br>';
echo 'State Name: ' + $obj->data->state_name;
你好。
我知道我正在回答這個問題,對於提出問題的用戶而言,這個問題已不再重要。 但是對於那些也面臨相同問題的人,可以從此示例中獲得幫助。
這就是為什么我要回答這個問題。
要運行以下代碼,請確保必須在系統中啟用curl。 否則它將無法正常工作。
<?php
if(isset($_POST['pincode']))
{
$pincode = $_POST['pincode'];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_URL => "https://pincode.saratchandra.in/api/pincode/" . $pincode
));
$resp = curl_exec($curl);
$temp = json_decode($resp);
if($temp->status ==200)
{
$records = $temp->data;
$str ="";
foreach ($records as $key => $values)
{
$str.= "pincode :" .$values->pincode."</br>";
$str.= "office_name :".$values->office_name."</br>";
$str.= "delivery_status :" .$values->delivery_status."</br>";
$str.= "division_name :".$values->division_name."</br>";
$str.= "region_name :" .$values->region_name."</br>";
$str.= "circle_name :".$values->circle_name."</br>";
$str.= "district :".$values->district."</br>";
$str.= "state_name :" .$values->state_name."</br>";
$str.= "taluk :".$values->taluk."</br><hr>";
}
echo $str;
curl_close($curl);
}
else
{
echo $temp->message;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>User Form</title>
</head>
<body>
<form name="user_form" method="post" action="" id="user_form">
<input type="pincode" name="pincode" value="" placeholder="Enter pincode" required="">
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
如果有任何問題,可以隨便問一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.