如何访问从PHP收到的ajax响应中的数组元素

How to access array elements in ajax response received from PHP?

本文关键字:ajax 响应 数组元素 PHP 何访问 访问      更新时间:2023-09-26

jajax函数的查询代码如下:

$(document).ready(function() {
$("#zip_code").keyup(function() {
    var el = $(this);
    var module_url = $('#module_url').val();
    if (el.val().length === 5) {
      $.ajax({
        url : module_url,
        cache: false,
        dataType: "json",
        type: "GET",
        data: {
            'request_type':'ajax', 
            'op':'get_city_state',
            'zip_code' : el.val()
        },
        success: function(result, success) { alert(result.join(''n'));
          $("#city").val(result.place_name);
          $("#state_code").val(result.state_code);
        }
      }); 
    }
  });
});

PHP代码片段如下:

case "get_city_state":
      // to get the city and state on zip code.
      $ret = $objUserLogin->GetCityState($request); 
      if(!$ret) { 
        $error_msg = $objUserLogin->GetAllErrors();
        list($data) = prepare_response($request);
        $smarty->assign('data', $data);    
      } else {
        $data = $objUserLogin->GetResponse();
        echo $data;
      }     
      die;
      break;

在PHP代码中,$data以以下方式包含数据:

<pre>Array
(
    [id] => 23212
    [zip_code] => 28445
    [place_name] => Holly Ridge
    [state_code] => NC
    [created_at] => 1410875971
    [updated_at] => 1410875971
)
</pre>

根据上面的数据(即响应,它将在ajax响应中的变量result中可用),我只想访问两个字段place_name和state_code。

我尝试在控制台中使用alert(result)打印结果变量的内容,但我得到了单词Array

如何实现这一点是我的疑问?

提前谢谢。

您应该将结果编码为json。因此,代替语句echo $data

使用

echo json_encode($data);

它将以json格式返回结果。像

{"id":23212,"place_name":"Holly Ridge"...}

在您的javascript中,您可以访问您的数据