如何使用Ajax将PHP文件的响应作为数组获取?

时间:2016-03-14 15:53:07

标签: javascript php json ajax

我试图通过按下一个按钮在HTML表单的文本框中输入邮政编码来获取完整地址,我有两个文件,第一个具有ajax功能,第二个具有PHP代码。我不确定我的ajax代码是否向PHP发送请求,任何人都可以帮助我吗?

这是ajax文件:

<script type="text/javascript">
$(document).ready(function(){
  $('.addressbutton').click(function(){
    ss=  document.getElementById("address").value;
    alert(ss);
    $.ajax({
      url: 'findaddress.php',
      type: 'post',
      data: ss,
      success: function(response){
        var replay = response.postal_code;
        alert(replay);
        document.getElementById('address').innerHTML = response.postal_code;
        document.getElementById('address2').innerHTML = response.route;
        document.getElementById('address3').innerHTML = response.locality;
        document.getElementById('address4').innerHTML = response.postal_town;
        document.getElementById('address5').innerHTML = response.administrative_area_level_2;
      }
    });
    return false;
  });
});
</script>

这是PHP代码(findaddress.php)

<?php
header('Content-Type: application/json');
$ss=$_POST['address'];
$postcode = urlencode($ss);
$url = 'http://maps.googleapis.com/maps/api/geocode/xml?
address='.$postcode.'&sensor=false';
$parsedXML = simplexml_load_file($url);

if($parsedXML->status != "OK") {
  echo "There has been a problem: " . $parsedXML->status;
}

$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
  if (is_array($component->type)) {
    $type = (string)$component->type[0];
  } else {
    $type = (string)$component->type;
  }

  $myAddress[$type] = (string)$component->long_name;
}
$f1 = $myAddress['postal_code'];
$f2 = $myAddress['route'];
$f3 = $myAddress['locality'] ;
$f4 = $myAddress['postal_town'] ;
$f5 = $myAddress['administrative_area_level_2'] ;
$f6 = $myAddress['country'];

//print_r($myAddress);
$ORegisertation = array(
  'postal_code' => $f1,
  'route' => $f2,
  'locality' => $f3,
  'postal_town' => $f4,
  'administrative_area_level_2' => $f5,
  'country' => $f6
);
$account_json = json_encode($ORegisertation);
echo $account_json;
?>

4 个答案:

答案 0 :(得分:1)

<强> HTML

<form name="frmRegistration" id="signup-form" method="post">
    <div>
        <input type="text" name="address" id="address" class="findaddress"  placeholder="Postal code"/>
        <input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" />
        <input type="text" name="address2" id="address2" class="findaddress"  placeholder="Line 1"/>
        <input type="text" name="address3" id="address3" class="findaddress"  placeholder="Line 2"/>
        <input type="text" name="address4" id="address4" class="findaddress"  placeholder="Line 3"/>
        <input type="text" name="address5" id="address5" class="findaddress"  placeholder="Line 4"/>
    </div>
 </form>

<强>的Javascript

$(document).ready(function(){
    $('.addressbutton').click(function(){
        ss =  document.getElementById("address").value;
        $.ajax({
            url: 'findaddress.php',
            type: 'post',
            data: {address:ss}, //added an index address here
            success: function(response){
                var replay = response.postal_code;
                //innerHTML is not an attribute of text boxes, so changed it to value
                document.getElementById('address').value  = response.postal_code;
                document.getElementById('address2').value = response.route;
                document.getElementById('address3').value = response.locality;
                document.getElementById('address4').value = response.postal_town;
                document.getElementById('address5').value = response.administrative_area_level_2;
            },
            error: function(response) {
                alert("Error: "+response);
            }
        });
        return false;
    }); //added closing brace and bracket
});

在脚本中添加了有关所做更改的注释。

PHP文件(findaddress.php)

<?php
header('Content-Type: application/json');
$ss         = $_POST['address'];
$postcode   = urlencode($ss);
$url        = 'http://maps.googleapis.com/maps/api/geocode/xml?address='.$postcode.'&sensor=false';
$parsedXML  = simplexml_load_file($url);

if($parsedXML->status != "OK") {
    echo "There has been a problem: " . $parsedXML->status;
}

$myAddress = array();
foreach($parsedXML->result->address_component as $component) {
    if(is_array($component->type)) $type = (string)$component->type[0];
    else $type = (string)$component->type;
    $myAddress[$type] = (string)$component->long_name;
}

echo json_encode($myAddress);
die();
?>

再次采取不相关的索引,以及不相关的陈述。

答案 1 :(得分:0)

您没有正确发送数据.. 如果你想获取php中的地址值,这是从ajax发布的,请执行此操作

data: { address: ss}, // 并在您的ajax中添加dataType:'json'或使用jsonParse(response)

你在回复中得到一个字符串,你无法直接使用response.postal_code;

答案 2 :(得分:0)

有一个带有html表单的ajax代码只是为了更好的想法

 <form name="frmRegistration" id="signup-form" method="post">

    <div><input type="text" name="address" id="address" class="findaddress"  placeholder="Postal code"/>
        <input type="button" name="addressbutton" class="addressbutton" value="Find" id="findaddress" onclick="javascript:hello()"/>
        <input type="text" name="address2" id="address2" class="findaddress"  placeholder="Line 1"/>
        <input type="text" name="address3" id="address3" class="findaddress"  placeholder="Line 2"/>
        <input type="text" name="address4" id="address4" class="findaddress"  placeholder="Line 3"/>
        <input type="text" name="address5" id="address5" class="findaddress"  placeholder="Line 4"/>
    </div>


    <script type="text/javascript">
     $(document).ready(function(){
         $('.addressbutton').click(function(){
             ss =  document.getElementById("address").value;
             //alert(ss);
             $.ajax({
                 url: 'findaddress.php',
                 type: 'post',
                 data: {address:ss},
                 success: function(response){
                     var replay = response.postal_code;
                     alert(replay);
                     document.getElementById('address').innerHTML = response.postal_code;
                     document.getElementById('address2').innerHTML = response.route;
                     document.getElementById('address3').innerHTML = response.locality;
                     document.getElementById('address4').innerHTML = response.postal_town;
                     document.getElementById('address5').innerHTML = response.administrative_area_level_2;
                 }
             });
             return false;
         }); //added closing brace and bracket
     });
    </script>
</form>

答案 3 :(得分:0)

在这种情况下,您需要确保从服务器定义响应类型。我喜欢放置dataType:&#39; json&#39;在我的$ .ajax电话中。然后在PHP代码中,确保添加application / json类型的标头。这将对某些浏览器产生影响。我想阅读Google Chrome的响应预览。它会自动解析响应;特别有助于调试。

header('Content-type: application/json');
echo json_encode($account_json);
exit;