如何使用jquery ajax获取api数据?

时间:2018-09-18 05:10:18

标签: php jquery json api

在此代码中,我有一个正常的下拉列表,其中有一些城市名称。现在,当我通过jquery更改任何城市时,我真正想要的是我想在尚未运行的警报框中获取json数据。不知道为什么那么,我该怎么做?

$(document).ready(function() {
  $("#city").change(function() {
    name = $(this).val();
    console.log(name);
    $.ajax({
      type: "POST",
      dataType: "json",
      data: {
        "name": name
      },
      url: "http://postalpincode.in/api/postoffice/" + name,
      success: function(data) {
        console.log(data);
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="city" id="city">
  <option value="">Select City</option>
  <option value="delhi">delhi</option>
  <option value="ghaziabad">ghaziabad</option>
  <option value="noida">noida</option>
  <option value="meerut">meerut</option>
</select>

1 个答案:

答案 0 :(得分:4)

请检查以下代码

<select name="city" id="city">
    <option value="">Select City</option>
    <option value="delhi">delhi</option>
    <option value="ghaziabad">ghaziabad</option>
    <option value="noida">noida</option>
    <option value="meerut">meerut</option>
</select> 

被称为Ajax

<script>
    $(document).ready(function(){
        $("#city").change(function(){
            name = $(this).val();
            /*For PHP called is for Cross-Origin Request Blocked*/
            $.ajax({
               type:"GET",
               dataType: "json",
               data:{name: name},
               url:"test.php",
               success:function(data)
               {
                   alert('Get Success');
                   console.log(data);
               }
            });
        });
    });
</script>

跨域请求被阻止的PHP文件代码-

<?php 
$name_city = rawurlencode($_GET['name']);
$url = "http://postalpincode.in/api/postoffice/".$name_city;
$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,"$url");
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_HEADER, false);
$postoffice_data = curl_exec($curl_handle);
curl_close($curl_handle); 
$postoffice_data = json_decode($postoffice_data);
echo json_encode($postoffice_data);
exit;
?>