如何在php中将多个json响应发送回ajax

时间:2017-09-04 05:04:51

标签: php mysql ajax

<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';

//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
if($res) {

    while($row = mysqli_fetch_assoc($res))
    {
        $array[]=$row ;
        $re['success']=true;
        $re['userObj']['firstname'] = $row['firstname'];
    }
}


else {
    $re['success']=false;
}
if(isset($_SESSION['username']))
{
    $sem=isset($_POST['sem'])?$_POST['sem']:'';
    $fname=isset($_POST['fname'])?$_POST['fname']:'';
    $year=isset($_POST['date'])?$_POST['date']:'';
    $query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");
    $re = array();
    while ($row = mysqli_fetch_assoc($query))
    {
        print_r($row);
        //$options['userObj'][]=$row;
    }
}

echo json_encode ($re);
return;
?>

这是我的完整PHP代码,我需要两个json响应, 1 GT;当我刷新页面时

$sql="call regtask2('$userid')";

此查询必须工作并将响应传递给ajax,然后我使用单击按钮。当我使用单击按钮时,此查询必须工作并传递响应

$query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");

我这是可能的?

2 个答案:

答案 0 :(得分:0)

这很简单只需将第二个查询结果添加到您以前的json!,还可以考虑在用户输入中添加一些验证以防止sql注入
从$ _POST获取用户ID是非常糟糕的主意

<?php
session_start();
$conn =new mysqli("localhost","root","","registration");
$userid=isset($_POST['userid'])?$_POST['userid']:'';

//$re['success']=false;
$sql="call regtask2('$userid')";
$res=mysqli_query($conn,$sql);
$array = array();
$re = array();
if($res) {
    $re['success']=true;
    while($row = mysqli_fetch_assoc($res))
    {
        $array[]=$row ;
        $re['userObj']['firstname'] = $row['firstname'];
    }
}


else {
    $re['success']=false;
}
if(isset($_SESSION['username']))
{
    $sem=isset($_POST['sem'])?$_POST['sem']:'';
    $fname=isset($_POST['fname'])?$_POST['fname']:'';
    $year=isset($_POST['date'])?$_POST['date']:'';
    $query = mysqli_query($conn,"select * from studentdetails inner join studentmarks on studentdetails.studentid=studentmarks.studentid where firstname='$fname' and sem='$sem'");

    while ($row = mysqli_fetch_assoc($query))
    {
        $re['userObj'][]=$row;
        //$options['userObj'][]=$row;
    }
}

echo json_encode ($re);
return;
?>

答案 1 :(得分:0)

3个选项:

  1. 只需拆分你的PHP代码。在刷新时,加载Dim TableNm_ As String = "Records" Dim restrictions2() As String = {Nothing, Nothing, TableNm_, Nothing} Dim DataTable2 As System.Data.DataTable = conn.GetSchema("Columns", restrictions2) 以及其他ajax调用,请加载script1.php
  2. 您需要为通话设置标识符。在你的ajax中,添加一个&#34; is_submit = true&#34;到查询。在你的php中,检查该值。
  3. 将您的返回值分配给$ return并返回该值。