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

时间:2021-10-24 07:51:20

I am trying to get a full address by entering the postal code in a textbox in HTML form by press a button, I have two files the first one has the ajax function and the second one has the PHP code. I am not sure if my ajax code sending a request to PHP or not, Can anyone help me please?

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

here is the ajax file:

这是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>

and here is the PHP code (findaddress.php)

这是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 个解决方案

#1


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
});

added comments in script about changes made.

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

PHP FILE (findaddress.php)

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

taken out irrelevant indexing again, and irrelevant statements.

取出不相关的索引再次和无关的陈述。

#2


0  

There is the ajax code with the html form just to have a better idea

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

You are not sending data correctly .. if you want to get value of address in php which is post from ajax do this

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

data: { address: ss}, // And Either add dataType:'json' there in your ajax or use jsonParse(response)

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

you get a string there at your response you cannot directly use response.postal_code;

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

#4


0  

In this case, you want to make sure to define the type of response from the server. I like to place dataType:'json' in my $.ajax calls. Then in your PHP code, make sure to add a header of type application/json. This will make a difference with some browsers. I like to read the Response Preview with Google Chrome. It will automatically parse the response; especially helpful with debugging.

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

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

#1


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
});

added comments in script about changes made.

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

PHP FILE (findaddress.php)

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

taken out irrelevant indexing again, and irrelevant statements.

取出不相关的索引再次和无关的陈述。

#2


0  

There is the ajax code with the html form just to have a better idea

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

You are not sending data correctly .. if you want to get value of address in php which is post from ajax do this

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

data: { address: ss}, // And Either add dataType:'json' there in your ajax or use jsonParse(response)

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

you get a string there at your response you cannot directly use response.postal_code;

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

#4


0  

In this case, you want to make sure to define the type of response from the server. I like to place dataType:'json' in my $.ajax calls. Then in your PHP code, make sure to add a header of type application/json. This will make a difference with some browsers. I like to read the Response Preview with Google Chrome. It will automatically parse the response; especially helpful with debugging.

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

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