如何在javascript中分离ajax响应数据

How to separate the ajax response data in javascript

本文关键字:ajax 响应 数据 分离 javascript      更新时间:2023-09-26

我有一个ajax函数,它从php页面返回一组值。我需要得到的值是唯一需要的。我该怎么做这个

ajax.js

function MakeRequest()
{
  var xmlHttp = getXMLHttp();
  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      HandleResponse(xmlHttp.responseText);
    }
  }
  xmlHttp.open("GET", "ajax.php", true); 
  xmlHttp.send(null);
}

ajax.php

<?php
require_once('config.php');
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM thr';
mysql_select_db($dbname);
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['ther_name'] . "</td>";
echo "<td>" . $row['region'] . "</td>";
echo "<td>" . $row['phone_no'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>

我只需要的值

 $row['corrd_lattitude'] 
 $row['corrd_longitude']

如何获取此的值

首先,您只能从表中获取所需的值。。如果我理解正确,您可以使用以下查询。

  $sql = 'SELECT corrd_lattitude,corrd_longitude FROM thr';

它将只返回表中的tw0列值。

 $json = json_encode(array($row['corrd_lattitude'],  $row['corrd_longitude']));
 echo $json;

您可以在请求中指定参数
在GET方法中:
ajax.php?corrd_lattitude=true&corrd_longitude=true
在php文件中,你可以在$_GET数组中检查这一点,即:

<?php
[...]
echo "<table border='1'>";
while($row = mysql_fetch_assoc($retval))
{
  echo "<tr>";
  if ($_GET['id'] == true) {
    echo "<td>" . $row['id'] . "</td>";
  }
  if ($_GET['ther_name'] == true) {
    echo "<td>" . $row['ther_name'] . "</td>";
  }
  if ($_GET['region'] == true) {
    echo "<td>" . $row['region'] . "</td>";
  }
  if ($_GET['phone_no'] == true) {
    echo "<td>" . $row['phone_no'] . "</td>";
  }
  if ($_GET['address'] == true) {
    echo "<td>" . $row['address'] . "</td>";
  }
  if ($_GET['corrd_lattitude'] == true) {
    echo "<td id='lat'>" . $row['corrd_lattitude'] . "</td>";
  }
  if ($_GET['corrd_longitude'] == true) {
    echo "<td id='lon'>" . $row['corrd_longitude'] . "</td>";
  }
  echo "</tr>";
}
echo "</table>";
mysql_close($conn);
?>

最好使用json(或纯值)而不是html——js应该将值打包到html中。对于服务器来说更好,客户端应该构建html。对不起我的英语。

use json:-----------
=========================================
$sql = "SELECT * FROM thr"; 
$rs = mysql_query($sql);
$res = mysql_fetch_assoc($rs);
if(mysql_num_rows($rs)>0){
echo json_encode(array('lats'=>$res['corrd_lattitude'],'lngs'=>$res['corrd_longitude']));
}else{
echo json_encode(array('lats'=>'','lngs'=''));
}

在这里,lats和lngs只是一个可变名称,用于在其中存储值,并从lats和lgs varaibale获取其他页面上的值。