Ajax从JS到PHP(到exec sql请求),然后从PHP到JS

时间:2019-06-12 10:23:27

标签: php jquery ajax post get

我正在使用$.ajax方法将数据从我的JS文件传递到我的PHP文件“ requetes.php”。这个PHP文件根据我的JS文件中的变量执行SQL请求。

我的Javascript:

$.ajax({
  url: 'requetes.php',
  type: 'POST',
  data: {
    datepicker: formattedDate
  },
  success: function(data) {             
    $("#sql-results").text(data);            
  },
  error: function(xhr) {
    console.log("echec de l'ajax !");
  }
})

在我的PHP文件中:

$rq_datepicker = "
    SELECT * 
    FROM partie
    WHERE date = '"$_POST['datepicker']"'";


$query = mysqli_query($connect, $rq_datepicker);
while ($result = mysqli_fetch_array($query)) {  
    echo "Il y a ".$result['Reussie']." partie(s)";
    echo "Il y a ".$result['Perdue']." partie(s);"
}

我减少了代码,因此更易于解释,但这很完美。 我可以从JS到PHP获取“ datepicker”变量,因此可以根据此变量执行SQL请求。 行$("#sql-results").text(data);从PHP文件返回我的2个回显。

我的问题是:

我只想从我的JS文件中访问这两个变量$result['Reussie']$result['Perdue']

我已经尝试了很多方法,例如将$ .ajax与GET方法或$ .get方法一起使用,但是没有成功。

4 个答案:

答案 0 :(得分:1)

首先,您的代码容易受到SQL注入的攻击,您必须使用 PDO with Prepared Statements 进行查询构建。

另一件事是,您只创建了一个具有键值对的数组,然后通过在json中进行编码来返回该数组。

示例:echo json_encode(array('foo' => 'bar'));

然后在ajax的js代码中,使用data解析var foo_result = JSON.parse(data['foo']);,现在您可以访问所需的变量。

请告诉我您是否达到要求。

答案 1 :(得分:0)

尝试这个:

$.ajax({
 url: 'requetes.php',
 type: 'POST',
 data: {
  datepicker: formattedDate
},
success: function(data) {             
   $("#sql-results").html(data);            
},
 error: function(xhr) {
   console.log("echec de l'ajax !");
 }
 });



$datepick = strip_tags($_POST['datepicker']);
$rq_datepicker = "
SELECT * 
FROM partie
WHERE date = '$datepick'";


$query = $connet->query($rq_datepicker);
while ($result = $query->fetch_assoc()) {  
        echo "Il y a ".$result['Reussie']." partie(s)";
        echo "Il y a ".$result['Perdue']." partie(s);"
    }
 }

答案 2 :(得分:0)

您必须以一种可以在JS中访问数据的方式来构造PHP响应。 为此,通常使用JSON,这种方式可以为您提供已处理的数据,而您只需要在JS中本地访问它们即可。

在这种情况下,您有2个要访问的变量。但是我想您也想将它们格式化为随后在jQuery中选择的某个对象。

要实现这一目标,有两种方法。

第一个-用PHP完成所有处理,然后仅使变量可用。

PHP方面:

$rq_datepicker = "
    SELECT * 
    FROM partie
    WHERE date = '"$_POST['datepicker']"'";


    $query = mysqli_query($connect, $rq_datepicker);
    while ($result = mysqli_fetch_array($query)) { 
            $response['dataRaw'] = array('Reussie' => $result['Reussie'],
                                     'Perdue' => $result['Perdue']);
            $response['dataProcessed'] = array('Reussie' =>  "Il y a ".$result['Reussie']." partie(s)",
                                    'Perdue' => "Il y a ".$result['Perdue']." partie(s)");
        }
    }
echo json_encode($response); // <-- using this will encode the variable according to the json specifics

一旦php处理了数据,在JS中,您只需在匿名函数中访问它们即可绑定到Ajax调用成功

JS端(如果HTTP请求为200):

success: function( data )
{               
    var response = JSON.parse(data);
    $("#sql-results").text(response.dataProcessed.Reussie+response.dataProcessed.Perdue);
    // to access the variables instead:
    // response.dataRaw.Reussie
    // response.dataRaw.Perdue
}

第二个-PHP只是将变量传递给JS,然后在此本地构建字符串。

PHP方面:

$rq_datepicker = "
    SELECT * 
    FROM partie
    WHERE date = '"$_POST['datepicker']"'";


    $query = mysqli_query($connect, $rq_datepicker);
    while ($result = mysqli_fetch_array($query)) { 
            $response['data'] = array('Reussie' => $result['Reussie'],
                                     'Perdue' => $result['Perdue']);
        }
    }
echo json_encode($response); // <-- using this will encode the variable according to the json specifics

在这种情况下,您没有预处理的数据,因此必须在本地构建字符串

JS端(如果HTTP请求为200):

success: function( data )
{               
    // to access the variables in this case:
    // response.data.Reussie
    // response.data.Perdue
    var response = JSON.parse(data);
    var stringReussie = "Il y a "+response.data.Reussie+" partie(s)";
    var stringPerdue = "Il y a "+response.data.Perdue+" partie(s)";
    $("#sql-results").text(stringReussie+stringPerdue);
}

一些额外的内容:

仅使用带有回显的json_encode作为输出而不声明响应类型,通常会将响应类型设置为“ application / json”。

echo json_encode($response);

为避免“通常”发生,并确保响应的内容类型部分为“ application / json”(如果是这种情况),还应设置响应的标头。

header("Content-type:application/json")

有关标题的更多信息:PHP Manual header()

关于json_encoding,请在此处阅读更多信息:https://www.php.net/manual/en/function.json-encode.php

答案 3 :(得分:0)

是的,没错!非常感谢 !所以我用了这个解决方案:

在我的PHP文件中:

$response['data'] = array('Reussie' => $result['Reussie'], 'Perdue' => $result['Perdue']);
echo json_encode($response);

在我的JS文件中:

var response = JSON.parse(data);
var stringReussie = "Il y a "+response.data.Reussie+" partie(s)";
var stringPerdue = "Il y a "+response.data.Perdue+" partie(s)";
$("#sql-results").text(stringReussie+stringPerdue);

我只是不明白为什么我不能放标题。看起来它“转换”了我所有的index.php文件。但这仍然有效,我想这很好。 :)

您太棒了!