[英]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.