繁体   English   中英

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

[英]How to get response from PHP file as an array using 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;
?>

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();
?>

再次取出不相关的索引,以及不相关的语句。

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

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

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

有一个带有 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>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM