在ajax成功函数中返回两个变量

时间:2014-12-08 21:42:14

标签: php jquery ajax

如何在单个功能中同时返回包裹编号和注释数量?我有两个单独的sql字符串返回不同的结果。我希望能够返回apn编号并将值放入标签以及有多少注释的计数。这可能吗?我该怎么做?

Jquery的:

$.ajax({
    url: "classes/get-apn-count-comments.php?parcel_id=" + parcel_id,
    type: "GET",
    data: { parcel_id : parcel_id },
    dataType: 'json',
    error: function(SMLHttpRequest, textStatus, errorThrown){
        alert("An error has occurred making the request: " + errorThrown);
    },
    success: function(data2){
        //do stuff here on success
        //$('#ParcelNumber').html(data[0]["apn"]);
        $('#ViewComments').val('View ' + data2[0].count + ' Comments');
    }
});

PHP:

<?php
require_once('../config.php');

if(isset($_GET['parcel_id'])) {
    $db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);

    //get the apn based on id
    //$data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
    //if($data != null) echo json_encode($data);

    //count number of comments for the id
    $data2 = $db->get_results("select count(*) as count from comments where parcel_id=" . $_GET['parcel_id']);
    echo json_encode($data2);
}

?>

1 个答案:

答案 0 :(得分:1)

在php端创建一个数组来同时回答一个并回答两个。然后json_encode并回显新的多维数组,就像使用旧数组一样。

然后在回调中的javascript端运行JSON.parse()将数组转换为javascript对象。

示例:

if(isset($_GET['parcel_id'])) {
  $db = new ezSQL_mysql(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  $return = array();
  //get the apn based on id
  $data = $db->get_results("select apn from parcels where parcel_id=" . $_GET['parcel_id']);
  if($data != null){
    $return['data_one'] = $data;   
  }

  //count number of comments for the id
  $data2 = $db->get_results("select count(*) as count from comments where parcel_id=" .$_GET['parcel_id']);
  if($data2 != null){
    $return['data_two'] = $data2;
  }
  echo json_encode($return);
}

JS:

success: function(res){
    //do stuff here on success
    res = JSON.parse(res);
    console.log(res);
}